I have an Order model:
const orderSchema = new mongoose.Schema({
order_items: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'OrderItem',
required: true
}],
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
shipping_address: {
type: String,
required: true
},
total_price: {
type: Number
}
});
And OrderItem model:
const orderItemSchema = new mongoose.Schema({
product_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true
},
unit_price: {
type: Number,
required: true
}
});
And Product model:
const productSchema = new mongoose.Schema({
name: {
type: Map,
of: String,
required: true
},
unit_price: {
type: Number,
required: true
}
});
I tried to do double populate on find Order in the request like this:
const findOrder = await Order.find({ user: user_id }).populate('order_items').populate({ path: 'order_items.product_id', select: 'name' });
But I get only the first populate. When I tried the following:
const findOrder = await Order.find({ user: user_id }).populate('order_items').populate({ path: 'product_id', select: 'name' });
I got this error:
Cannot populate path
product_id
because it is not in your schema. Set thestrictPopulate
option to false to override.
How can I get the product's name in a nested populate request?
Thanks...
CodePudding user response:
Try with:
const findOrder = await Order.find({ user: user_id })
.populate({
path: 'order_items',
populate: {
path: 'product_id',
select: 'name'
}
}).exec();
For more information about the population across multiple levels read here.