我需要实现一个功能,其中发布的每个产品都会增加相应类别和子类别的产品数量。 这是我的架构:
//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/