【问题标题】:How to populate the ObjectId inside an array?如何在数组中填充 ObjectId?
【发布时间】:2021-03-15 14:58:24
【问题描述】:
  {
    orders: {
      userID: { type: Schema.Types.ObjectId, ref: 'User' },
      order: [
        {
          productID: { type: Schema.Types.ObjectId, ref: 'Inventory' },
          quantity: { type: Number },
          vendorCoupon: { type: String },
        },
      ],
     }
  }

我有一个类似这样的 orderSchema。我可以这样填充用户 ID:

Order.find({ userID: req.body.userID }).populate('userID') 
 ... some other code snippet ...

但是我应该如何在这个订单数组中填充 productID 呢?我必须映射数组中的所有产品 ID。我该如何实现它?

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

    试试这个,

    Order.find({ userID: req.body.userID }).populate('userID').populate({
      path: 'order.productID'
    });
    

    另见:https://mongoosejs.com/docs/populate.html#deep-populate & Populate nested array in mongoose

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2017-04-20
      • 2021-01-06
      • 2014-11-05
      • 2021-08-25
      • 2020-08-15
      • 1970-01-01
      • 2021-12-05
      • 2016-05-09
      相关资源
      最近更新 更多