如何在数组中填充 ObjectId?

问题描述

  {
    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。我该如何实施?

解决方法

试试这个,

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