2

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?

Nux
  • 5,890
  • 13
  • 48
  • 74

1 Answers1

0

You can use the filtered positional operator (MongoDB 3.6 or newer) to define a condition which will identify your 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);
    });
};
mickl
  • 48,568
  • 9
  • 60
  • 89
  • Thanks for response. I have copied and pasted the above code in my project but only productsCounts in **Category** increases and not in specific subcategory. Here is the log i get `{ productsCounts: 108, _id: 5c8ab97c4835f2316811d41d, title: 'Guests', subcategories: [ { productsCounts: 0, properties: [], _id: 5c8ab99d4835f2316811d41e, title: 'Bondeni' }, { productsCounts: 0, properties: [], _id: 5c8ab9ba4835f2316811d420, title: 'Tema' } ], __v: 0 }` – Nux Mar 17 '19 at 11:19
  • What could still be wrong? – Nux Mar 17 '19 at 11:20
  • After updating mongoose version to latest it now works. Thanks for – Nux Mar 17 '19 at 12:20
  • can you take a look at my other question. they are kind related. [link](https://stackoverflow.com/questions/55217447/mongoose-upsert-and-inc-subdocument) @mickl – Nux Mar 18 '19 at 14:29