Search code examples
postgresqlexpresspopulateentitiesmikro-orm

Is it possible to choose the properties of nested entities in mikro-orm?


I'm working in the following simple setup in a backend controller using mikro-orm and express:

const getOrigins = async (_: Request, res: Response) => {
  try {
    const origins = await orm.em.find(Origin, {}, { populate: ['country'] });
    res.status(200).send(origins);
  } catch (error) {
    console.error(error);
    res.status(500).send(error);
  }
};

These are a simplified version of the entities that I'm using:

export abstract class Base<T extends { id: string }> extends BaseEntity<T, 'id'> {
  @PrimaryKey({ type: 'uuid' })
  public id: string = v4();

  @Property()
  public createdAt: Date = new Date();

  @Property({ onUpdate: () => new Date() })
  public updatedAt: Date = new Date();

  constructor(body = {}) {
    super();
    this.assign(body);
  }
}

@Entity()
export class Country extends Base<Country> {
  @Property()
  @Unique()
  country: string;

  @OneToMany(() => Origin, o => o.country)
  origins = new Collection<Origin>(this);

  constructor(country: string) {
    super();
    this.country = country;
  }
}

@Entity()
export class Origin extends Base<Origin> {
  @ManyToOne(() => Country, { cascade: [Cascade.PERSIST] })
  country;

  constructor(country: Country) {
    super();
    this.country = country;
  }
}

The code should return a list of origins populated with the country. So far the code is working fine but it's returning the following object:

[
  {
    "id": "0cda300f-57a3-406f-8167-271ee1db519f",
    "createdAt": "2021-03-06T22:19:54.000Z",
    "updatedAt": "2021-03-06T22:19:54.000Z",
    "country": {
      "id": "801a73af-4fc7-46d7-b5c4-0f8fcd2024d5",
      "createdAt": "2021-03-06T22:10:58.000Z",
      "updatedAt": "2021-03-06T22:10:58.000Z",
      "country": "UK"
    }
  }
]

Is there a way to filter the returned properties of the nested entities using the query parameters so that it returns a much simpler object like:

[
  {
    "id": "0cda300f-57a3-406f-8167-271ee1db519f",
    "createdAt": "2021-03-06T22:19:54.000Z",
    "updatedAt": "2021-03-06T22:19:54.000Z",
    "country": "UK"
  }
]

I have tried multiple syntax variations but I can't seem to find the right one. Docs on mikro-orm are not too clear on this specific case. Thanks in advance for your help


Solution

  • There are few things you can do: