Reputation: 774
I am trying to populate a nested object with mongoose. I have a document which contains a list of product or service. I am using refPath to add it dynamically. The problem is when I am trying to populate product/service from path this does not work.
Here my scheme:
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},
}
],
});
Then I have my request :
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 });
});
Upvotes: 1
Views: 3121
Reputation: 774
I find the solution ! I modify the refPath by adding array name so it look like
instead of refPath: "onModel"
now is : "list_items.onModel"
Here is the updated schema :
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}
}
],
})
Then
mongoose.model(model).findOne({ company_id: mongoose.Types.ObjectId(company_id), _id: mongoose.Types.ObjectId(id) })
.populate('list_items.item_id')
//....
Upvotes: 18