对Model.find进行双重填充



我有一个订单模型:

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
}
});

和OrderItem模型:

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
}
});

和产品型号:

const productSchema = new mongoose.Schema({
name: {
type: Map,
of: String,
required: true
},
unit_price: {
type: Number,
required: true
}
});

我尝试在请求中查找订单时进行double填充,如下所示:

const findOrder = await Order.find({ user: user_id }).populate('order_items').populate({ path: 'order_items.product_id', select: 'name' });

但是我只得到第一个填充。当我尝试以下操作时:

const findOrder = await Order.find({ user: user_id }).populate('order_items').populate({ path: 'product_id', select: 'name' });

我得到这个错误:

不能填充路径product_id,因为它不在您的模式中。将strictPopulate选项设置为false以覆盖。

如何在嵌套的填充请求中获得产品名称?

谢谢…

Try with:

const findOrder = await Order.find({ user: user_id })
.populate({
path: 'order_items',
populate: {
path: 'product_id',
select: 'name'
} 
}).exec();

有关多个级别人口的更多信息,请阅读此处。

最新更新