node.js - 在子文档数组中使用 mongoose $inc

标签 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?

最佳答案

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

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);
    });
};

关于node.js - 在子文档数组中使用 mongoose $inc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201417/

相关文章:

javascript - “发送到客户端后无法设置 header ” - 我正在设置 header ,但找不到位置

java - Mongo、spring 和序列化

javascript - 更新 Mongoose 模型内的数组

javascript - 在一次调用中推送 mongoose 中的数组列表

mongodb - 使用 Mongo 查询数组元素

javascript - 为什么 mongoose populate 在填充数组时不起作用?

javascript - 如何在模式上覆盖 Mongoose findOne() 函数以进行测试?

django - 与 Django 一起使用时 ReactJS 中的 SEO

javascript - Nodejs中将Buffer数据对象转换为数组

Javascript 将函数的返回值转换为变量