0

I am trying to update the value of an object in an array of my mongodb schema using mongoose and nodejs.

My model is :

{
"_id": ObjectId("557eecd687cff9281040efe5"),
"products": [
    {
        "productId": "6849500",
        "qty": 2,
        "_id": ObjectId("557eef13101aef4c101af513")
    }
]
}

I would like to update the "products" array "qty" value filtering on "productId"

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
user1374021
  • 196
  • 1
  • 9

2 Answers2

1

Try the following update which uses the $ positional operator to identify an element in an array to update without explicitly specifying the position of the element in the array. Since the positional $ operator acts as a placeholder for the first element that matches the query document, the array field must appear as part of the query document hence you need the products array field in your query:

db.collection.update(
    {"products._id": ObjectId("557eef13101aef4c101af513")}, 
    {"$set": {"products.$.qty": 8} }
)  
chridam
  • 100,957
  • 23
  • 236
  • 235
0

You will have to use the operator $.

ModelName.update({
  //find the document
},{
  products.$.qty : //value
});

ALITER

Maybe you will have to make a new object

{
    "productId": "6849500",
    "qty": //some new value,
    "_id": ObjectId("557eef13101aef4c101af513")
}

and then update the document,

I personally think that the second approach will be more safe and sound.

MegaMind
  • 653
  • 6
  • 31