I need to implement a functionality where every product posted will increase product counts of respective category and subcategory. This is my schema:
//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)
});
};
The above code works for category productCounts well. How can update specific subcategory productCounts too?