我有这两个 3 模型 User、Product 和 Orders,并且它们也相互引用。
我的订单架构:
const orderSchema = Schema({
buyerId:{
type: Schema.Types.ObjectId,
ref: 'User'
},
totalAmount: {
type: Number,
required: [true, "description is required"]
},
createdOn: {
type: Date,
default: new Date()
},
items:[{type:Schema.Types.ObjectId, ref: 'Product'}]})
我正在尝试像这样使用 populate():
Order.find()
.populate('buyerId')//Reference to User Model
.populate('items')// Reference to Product Model
.exec(function (err, result){
console.log(result);// RETURNS ONLY buyerId populated
console.log(result.buyerId.name);//Successfully references to my User model and prints name
console.log(result.items);//Prints Undefined
})
您可以在上面看到我的控制台日志,它返回的只是填充的buyerId(仅从我的用户模型中获得参考)
似乎我的 populate('items') 根本不起作用。items 字段包含 ID 数组,其中 ID 是产品的 ID。我需要同时参考用户和产品。我只是在关注猫鼬中的文档,我不知道我可能做错了什么。
使用聚合
Order.aggregate([
{ $match:{ user:"sample_id"
}
},
{$lookup:{
from:'users', // users collection name
localField:'buyerId',
foreignField:'_id',
as:'buyerId'
}},
{
$lookup:{
from:'items', //items collection name
localField:'items',
foreignField:'_id',
as:'items'
}
},
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句