首页 > 解决方案 > Mongoose:使用对象数组查找所有模型

问题描述

我有这个模型:

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.jsmongodbmongoosemongoose-schema

解决方案


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

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

推荐阅读