在子文档数组中使用猫鼬$ inc

时间:2019-03-16 20:56:53

标签: node.js mongodb mongoose

我需要实现一项功能,其中发布的每个产品都会增加相应类别和子类别的产品数量。 这是我的架构:

//Subcategory
const subcategorySchema = new mongoose.Schema({
    title: {type: String},
    productsCounts: {type: Number, default: 0},
});

//Category
const categorySchema = new mongoose.Schema({
    title: {type: String},
    subcategories: [subcategorySchema],
    productsCounts: {type: Number, default: 0}
});

//Method I use to update products count
categorySchema.statics.increaseProductsCounts = function (categoryId, subcategoryId) {
    //Increase category's productCounts.
    this.findByIdAndUpdate(categoryId, {$inc: {productsCounts: 1}}).then(r => {
        console.log(r)
    });
};

上面的代码适用于productCounts类。怎样也可以更新特定的子类别productCounts?

1 个答案:

答案 0 :(得分:0)

您可以使用filtered positional operator(MongoDB 3.6或更高版本)来定义一个可以识别您的subcategory的条件:

categorySchema.statics.increaseProductsCounts = function (categoryId, subcategoryId) {
    this.findByIdAndUpdate(categoryId, 
        {$inc: {productsCounts: 1, 'subcategories.$[sub].productsCounts': 1}}, 
        { arrayFilters:[ { 'sub._id': subcategoryId } ] }).then(r => {
            console.log(r);
    });
};