How to overwrite an exisiting object inside a array

Hello everyone,

I am trying to overwrite a existing object that is inside a array. This is the structure:

 - Array:
shoppingcart: 
  - Object0:
"productname": shoppingcartproduct0name,   
"productamount": 1,
"productimage": shoppingcartproduct0image,
"productprice": shoppingcartproduct0price

So as you can see the object is inside the array. Now I am trying to accomplish this with a set operator:

$set: {
shoppingcart: {
"productname": shoppingcartproduct0name,
"productamount": quantity0,
"productimage": shoppingcartproduct0image,
"productprice": shoppingcartproduct0price,
}
}

However if I try this then instead of updating the object, MongoDB just ignores the fact that the “shoppingcart” was an array and butchers it to make it a object instead. So it ends up like this:

  - Object0:
shoppingcart: 
"productname": shoppingcartproduct0name,   
"productamount": quantity0,
"productimage": shoppingcartproduct0image,
"productprice": shoppingcartproduct0price

Which is not what I want because the “shoppingcart” has to stay as an array and not change to an object. With the field “productamount” beign overwritten from 1 to “quantity0”

I have asked around and someone gave me a solution. For anyone else that has this problem:

$set: {
"shoppingcart.0": {
"productname": shoppingcartproduct0name,
"productamount": quantity0,
"productimage": shoppingcartproduct0image,
"productprice": shoppingcartproduct0price,
}
}

Change the number in this case 0 to match any of the objects inside the array.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.