首页 > 解决方案 > TypeORM 官方关系示例不起作用

问题描述

我希望能够保存并返回用户列表及其相关办公室。为此,我根据文档、nestJS、typeORM 和 mongoDB使用官方的一对一关系

用户实体.ts

@OneToOne(() => Office, office => office.user) // specify inverse side as a second parameter
@JoinColumn()
office: Office;

办公实体.ts

@OneToOne(() => User, user => user.office) // specify inverse side as a second parameter
user: User;

保存用户

const officeId = "615c190d9a99101c6ca6cf43"
const officeObject = await this.officesService.findOne(officeId);
user.office = officeObject; 
const createdUser = await this.usersService.save(user); // user is an object coming from the request and not an actual model instance

以下方法不返回办公室参考

const users = await this.usersRepository.find({
    select: ['id', 'firstName', 'lastName', 'email', 'role', 'office'],
    relations: ['office']
});

我究竟做错了什么?

标签: foreign-keystypeormrelation

解决方案


TypeOrm 似乎并不容易自动处理关系:https ://github.com/typeorm/typeorm/issues/655

ManyToOne/OneToMany/ManyToMany/OneToOne - 这些装饰器仅在关系数据库中受支持,MongoDB 不支持。Mongodb 是无关系的,所以你不能像在关系数据库中那样轻松地做你想做的事。您应该手动加载所需的数据(组)并将其手动设置为您的实体(用户)。

也许会有这样的功能,但它很复杂,而且我现在正忙于其他任务,所以不会在不久的将来。


推荐阅读