Home > Enterprise >  Mongo DB Update data
Mongo DB Update data

Time:04-30

I want to decrease previours quantity by 1 how can I do this in Node Js Mongo Db

Here is my code:

        app.put('/quantityUpdate',async(req,res)=>{
            const id = req?.body?.id;
            const dec= req?.body?.dec;
            const filter = {_id:ObjectId(id)}
               // this option instructs the method to create a document if no documents match the filter
            const options = { upsert: true };
            const updateDoc = {
                $set: {
                    quantity: //I'm stuck in this place
                },
              };
            const result = await products.updateOne(filter, updateDoc, options);
            return res.send(result);
        })

CodePudding user response:

Instead of $set use $inc. It increments a field by a specified value.

To decrease the value by 1 you change your code to:

const updateDoc = { $inc: { quantity: -1 } }

To get more details, checkout the documentation.

  • Related