Home > other >  How to increment then save an object in mongodb database with node js?
How to increment then save an object in mongodb database with node js?

Time:11-24

I'm trying to increment the quantity of an object inside of an array from mongodb database then save it like this :

      await user.cart.items.find((each) => {
        if (JSON.stringify(each._id) === JSON.stringify(productId)) {
          if (each.instock > each.quantity) {
            each.quantity  = 1;
            console.log("Incremented");
          }
        }
      });
      console.log(user.cart.items);
      await user.save();

When I console log user.cart.items the field quantity is incremented successfully but when I go to database it is not . Basically the code await user.save(); doesn't seem to work .

How can I save the newly updated object in mongodb database with node js ?

CodePudding user response:

I solved the issue by implementing this piece of code before saving the user model :

 user.markModified("cart");
 await user.save();
  • Related