猫鼬填充多个级别

时间:2020-06-27 07:23:43

标签: node.js mongodb mongoose mongoose-populate

我有一个具有订单密钥的用户集合:

orders:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Order'
    }]

订单架构包含一系列产品:

contents:[{
        product:{
            type:String,
            ref:'Product'
        },
        size:String,
        color:String,
        price:Number
    }]

并且产品架构的_id为:

_id:{
        type:String,
        unique:true,
        required:true
    }

现在,我想返回用户以及该订单中他的订单和产品的所有详细信息。

我尝试过此操作,但是它没有在订单中填充产品详细信息:

User.findById(req.user._id)
    .populate("orders")
    .populate("orders.contents.product")

当我尝试填充一个订单时,它可以正常工作:

Order.findById(req.params.orderId)
    .populate("contents.product")

1 个答案:

答案 0 :(得分:0)

您可以尝试嵌套方法,在您的情况下,该方法应类似于:

.populate({ 
  path: 'orders',
  populate: {
    path: 'contents.product'
  } 
})

https://mongoosejs.com/docs/populate.html#populate_multiple_documents