Reputation: 434
I have a collection of Product, the client post and Order request with an array of objects every single object contains the _id product (objectId) and the quantity he bought.
[
{producId: "dshsdsdh72382377923",
quantity: 20
},
{producId: "dsh673sdh72382377923",
quantity: 10
},
{producId: "hjddjkdjkdj676372373",
quantity: 5
},
]
I want to query the Product Collection and decrement (Update) the numberInStock of every product with the quantity that the client bought ! How can i do it ?
Upvotes: 0
Views: 35
Reputation: 575
Build dynamic query based on how many items user purchased. Select the product by it's productId
and decrement the quantity by customerValue
let customerValue = 4; // Let's say the customer bought 4 items
let query = {};
query['quantity'] = -customerValue;
db.collection.updateOne(
{producId : "hjddjkdjkdj676372373"},
{$inc: query}
);
Upvotes: 1