我正在使用 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",
"createdAt": "2021-03-06T22:19:54.000Z",
"updatedAt": "2021-03-06T22:19:54.000Z",
"country": "UK"
}
]
我尝试了多种语法变体,但似乎找不到合适的。mikro-orm 上的文档在这个具体案例上不太清楚。在此先感谢您的帮助