【发布时间】:2019-09-12 01:29:07
【问题描述】:
所以基本上,在我的应用程序中,我有一个员工和一个公司模型。这只是关于这些模型的基本信息,实际上还有更多信息,因此使用嵌套对象而不是 2 个模式似乎不是一个好的选择(我认为)
var EmployeeSchema = new Schema(
{
name: { type: String, required: true, max: 100 },
company: { type: Schema.Types.ObjectId, ref: 'Company', required: true },
}
);
var CompanySchema = new Schema(
{
name: { type: String, required: true },
},
{
toJSON: { virtuals: true },
},
);
CompanySchema.virtual('employees', {
ref: 'Employee',
localField: '_id',
foreignField: 'company',
justOne: false,
});
在创建新员工的表单上,我希望选择公司或创建新公司。
所以我的 API 将发送如下信息:
employee: {
name: 'John Bastien',
company: 5d44635fa5993c0424da8e07
}
或:
employee: {
name: 'Dan Smith',
company: {
name: 'ACME'
}
}
这当然是可以改变的,这正是我的想法。
所以在我的快递应用程序中,当我做var employee = await new Employee(req.body.employee).save(); 时,我怎样才能使公司与员工一起创建。发送对象 ID 时效果很好,但我怎样才能只使用关联文档的 JSON 对象呢?
【问题讨论】: