我试图用猫鼬填充嵌套对象。我有一个包含产品或服务列表的文档。我正在使用refPath来动态添加它。问题是,当我尝试从路径填充产品/服务时,此方法不起作用。
这是我的计划:
const quoteSchema = new Schema({
other: {type: String},
list_items: [
{
item_id: {
type: Schema.ObjectId,
require: true,
refPath: "type"
},
type: {
type: String,
required: true,
enum: ['service', 'product']
},
quantity: {type: Number},
desc: {type: String},
discount: {type: Number},
unit_price: {type: Number},
total: {type: Number},
}
],
});
然后我有我的要求:
mongoose.model(model).find({ company_id: mongoose.Types.ObjectId(company_id), _id: mongoose.Types.ObjectId(id) })
.populate([{
path: 'list_items.item_id',
model: 'list_items.type'
}])
.lean()
.exec( (err, doc) => {
return res.json({ success: true, payload: doc });
});
答案 0 :(得分:0)
我找到了解决方案!我通过添加数组名称来修改refPath,使它看起来像
代替refPath:“ onModel”
现在是:“ list_items.onModel”
这是更新的架构:
const quoteSchema = new Schema({
list_items: [
{
item_id: {
type: Schema.ObjectId,
require: true,
refPath: "list_items.onModel"
},
onModel: {
type: String,
required: true,
enum: ['service', 'product']
},
quantity: {type: Number},
desc: {type: String},
discount: {type: Number},
unit_price: {type: Number},
total: {type: Number},
ref: {type: String}
}
],
})
然后
mongoose.model(model).findOne({ company_id: mongoose.Types.ObjectId(company_id), _id: mongoose.Types.ObjectId(id) })
.populate('list_items.item_id')
//....