app.put('/product/:id', async(req, res) =>{
const id = req.params.id;
const updateQuantity = req.body;
const filter = {_id: ObjectId(id)};
const options = { upsert: true};
const updateDoc = {
$set: {
productQuantity: updateQuantity.productQuantity
}
};
const result = await productCollection.updateOne(filter, updateDoc, options);
res.send(result);
})
//this code only can replace the quantity can’t increase or decrease the quantity.
2
Answers
You can try the increment operator
$inc
along withfindOneAndUpdate
. The code would change as follows:To decrease the value:
const updateDoc = {$inc : {'productQuantity' : -1}};
To increase the count by 5.
To Decrement the count by 5
Now make sure the value passed to the
productQuantity
is aNumber
and not a string. You can do that by passingupdateQuantity.productQuantity
in Number constructor likePS:
product.productQuantity
is a bad name. Tryproduct.quanlity
next time.