user8078238
user8078238

Reputation:

How to update an array with his index number in Mongoose

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

Answers (1)

wak786
wak786

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

Related Questions