【问题标题】:Mongoose: Find all Models using array of objectsMongoose:使用对象数组查找所有模型
【发布时间】:2020-07-27 06:12:06
【问题描述】:

我有这个模型:

const cart = new mongoose.Schema(
  {
    products: [{
        productId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Product",
        },
        quantity: {
            type: Number,
            required: true,
            default: 1
        },
        title: String,
        price: Number
    }],
  },
  { timestamps: true });

我如何使用它找到我的所有产品(来自 Model Product)。

cart = Cart.find(id);

// inside cart.products
[{productId: 'asvhbajAS13', quantity: 8 },{productId: 'asvhbajAS13', quantity: 2 }]

之后我想修改所有产品,这样的做法对吗?

我尝试过的:

Product.find({
                '_id': { $in: { cart.products } }
             }, function(err, product) {
              
                })
        });

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    您的代码是正确的,但如果您使用 findOne() 或者您可以再次使用填充而不是查询:

    cart = Cart.find(id).populate("products")
    

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 2020-09-15
      • 1970-01-01
      • 2019-08-03
      • 2021-07-02
      • 1970-01-01
      • 2016-07-28
      • 2019-06-22
      • 2020-04-12
      相关资源
      最近更新 更多