是否可以在 mikro-orm 中选择嵌套实体的属性?

问题描述

我正在使用 mikro-orm 和 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);
  }
};

这些是我正在使用的实体的简化版本:

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;
  }
}

代码应返回填充了该国家/地区的原产地列表。 到目前为止,代码运行良好,但返回以下对象:

[
  {
    "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"
    }
  }
]

有没有办法使用查询参数过滤嵌套实体的返回属性,以便它返回一个更简单的对象,例如:

[
  {
    "id": "0cda300f-57a3-406f-8167-271ee1db519f","country": "UK"
  }
]

我尝试了多种语法变体,但似乎找不到合适的变体。 mikro-orm 上的文档对此特定案例不太清楚。 预先感谢您的帮助

解决方法

您可以做的事情很少: