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"

1
  • Hint: {$set:{'products.$.qty':'qty_value '}. Commented Jun 22, 2015 at 9:50

2 Answers 2

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} }
)  
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Okay. I guess nested $ are not supported. Thanks i will update my answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.