Reputation:
my User Model has an cart with items (Array). I want to check if there is enough stock for each item in his cart and if not, to update the quantity of the item in his cart to the available stock (productId is populated).
}
})
Well 'cart.items[i].quantity' would be too easy, it's not working :D
User: [![enter image description here][1]][1]
Product: [![enter image description here][2]][2]
Upvotes: 1
Views: 978
Reputation: 1615
This is the code you provided.
user.cart.items.forEach((item, i) => {
if (item.quantity > item.productId.stock) {
User.findByIdAndUpdate(user._id, {'cart.items[i].quantity': item.productId.stock})
}
})
From the above code i can see that we have the productId
of the item to be updated. So why use index when we have productId
? Anyways i have created a sample document based on your screenshots and created a query which updates the quantity
based on productId
. You can go to the mongo playground link and run the query and do tweaks as per your needs.
Try this query-
db.collection.update({
_id: 1
},
{
"$set": {
"cart.items.$[element].quantity": 2 /**where 2=item.productId.stock*/
}
},
{
arrayFilters: [
{
"element.productId": 100
}
]
})
Here is Mongo Playground
Edit :
If you still want to do it with index.
db.collection.update({
_id: 1
},
{
"$set": {
"cart.items.1.quantity": 2/**where 1 is index and 2=item.productId.stock*/
}
})
Here is playground
Upvotes: 3