Home:ALL Converter>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?

Ask Time:2021-11-22T06:17:57         Author:Mehdi Faraji

Json Formatter

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 ?

Author:Mehdi Faraji,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70059061/how-to-increment-then-save-an-object-in-mongodb-database-with-node-js
yy