Redwan
Redwan

Reputation: 47

Mongo DB Update data

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);
        })

Upvotes: 0

Views: 47

Answers (1)

SudhanshuSuman
SudhanshuSuman

Reputation: 53

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.

Upvotes: 1

Related Questions