I am working on an inventory system management using MongoDB,ExpressJs,ReactJs,Express, and my question is – how I can update a product quantity after completing it’s order?
let me explain: if the product quantity in stock is 10 for example,then after ordering like 3 ,I want the product quantity to be 7 directly…
2
Answers
You have to write separate your own logic for this however I can share the common logic which can be used.
Let’s say you store the products in this way ( example ) :
{product : 'apple', quantity : 10, productId : 121 }
then,
Once you receive new
order
, use theproduct name
orproductId
( I suggest using productId ), useproducts.findOneAndUpdate({ productId : productId }, $inc: {quantity : ( 0 - orderQuantity) }, (err, updatedData) => {})
Here you might have to change the
products.findOneAndUpdate
toproducts.updateOne
based on whether you are using mongoose or MongoDB.also
productId
is the productId you received from the request.And
orderQuantity
is the quantity of the orders.I didn’t find from where you are taking the
_id
to update the products collection.And
orderItems
is an array so you won’t get quantity inside of it.You have to loop through each item of
orderItems
and update the collection.Note :
send the response once after the complete process.
In the code, you sent before updating the quantity, I have changed the above code with whatever I could do.