【问题标题】:Mongoose populate multiple levels猫鼬填充多个级别
【发布时间】:2020-10-17 18:52:41
【问题描述】:

我有一个包含 orders 键的 users 集合:

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

orders 模式有一个产品数组:

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")

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    您可以尝试嵌套方法,在您的情况下应该如下所示:

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-13
      • 1970-01-01
      • 2017-02-25
      • 2015-07-13
      • 2016-10-10
      • 2021-11-07
      • 2019-09-16
      • 2015-07-13
      相关资源
      最近更新 更多