【发布时间】:2021-02-21 14:08:50
【问题描述】:
所以我正在使用 NestJs 和 Typegoose 构建一个后端,具有以下模型:
部门
@modelOptions({ schemaOptions: { collection: 'user_department', toJSON: { virtuals: true }, toObject: { virtuals: true }, id: false } })
export class Department {
@prop({ required: true })
_id: mongoose.Types.ObjectId;
@prop({ required: true })
name: string;
@prop({ ref: () => User, type: String })
public supervisors: Ref<User>[];
members: User[];
static paginate: PaginateMethod<Department>;
}
用户
@modelOptions({ schemaOptions: { collection: 'user' } })
export class User {
@prop({ required: true, type: String })
_id: string;
@prop({ required: true })
userName: string;
@prop({ required: true })
firstName: string;
@prop({ required: true })
lastName: string;
[...]
@prop({ ref: () => Department, default: [] })
memberOfDepartments?: Ref<Department>[];
static paginate: PaginateMethod<User>;
}
您可能已经猜到,一个用户可能在多个部门,而一个部门可以有多个成员(用户)。由于部门的数量或多或少受到限制(与用户相比),我决定使用一种嵌入方式,如下所述:Two Way Embedding vs. One Way Embedding in MongoDB (Many-To-Many)。这就是用户持有数组“memberOfDepartments”的原因,但部门不保存成员数组(因为缺少@prop)。
第一个问题是,当我请求Department-object时,如何查询它的成员?查询必须查找 department._id 在数组 memberOfDepartments 中的用户。
我在这里尝试了多种东西,例如虚拟填充:https://typegoose.github.io/typegoose/docs/api/virtuals/#virtual-populate 就像在 department.model 上这样:
@prop({
ref: () => User,
foreignField: 'memberOfDepartments',
localField: '_id', // compare this to the foreign document's value defined in "foreignField"
justOne: false
})
public members: Ref<User>[];
但它不会输出该属性。我的猜测是,这仅适用于一个站点上的一对多...我也尝试使用 set/get,但在 DepartmentModel 中使用 UserModel 时遇到问题。
目前我在服务中这样做是在“作弊”:
async findDepartmentById(id: string): Promise<Department> {
const res = await this.departmentModel
.findById(id)
.populate({ path: 'supervisors', model: User })
.lean()
.exec();
res.members = await this.userModel.find({ memberOfDepartments: res._id })
.lean()
.exec()
if (!res) {
throw new HttpException(
'No Department with the id=' + id + ' found.',
HttpStatus.NOT_FOUND,
);
}
return res;
}
.. 但我认为这不是正确的解决方案,因为我猜它属于模型。
第二个问题是,我将如何处理一个部门的删除,导致我必须删除对该部门的引用。在用户中?
我知道那里有 mongodb 和 mongoose 的文档,但我只是无法理解如何以“typegoose 方式”完成此操作,因为 typegoose 文档对我来说似乎非常有限。任何提示表示赞赏。
【问题讨论】:
标签: mongodb typescript mongoose typegoose