How to push a new value to a nested array in Mongoose How to push a new value to a nested array in Mongoose mongoose mongoose

How to push a new value to a nested array in Mongoose


You can use $push to do this.

Example:

YourModel.findOneAndUpdate(condition, {$push: {"fixtures.0.fixture2": "vote4"}})


You can use below query

update(  { "fixtures.fixture2": { "$exists": true } },  { "$push": { "fixtures.$.fixture2": "vote4" } })


You can use $(update) positional operator to achieve this.

Also, don't forget to use {multi : true} in your update options, to update all the documents in your collection.

Try this :

Votes.update(  { "fixtures.fixture2": { "$exists": true } },  { "$push": { "fixtures.$.fixture2": "vote4" } },  { multi : true})

But this will only update the first matched fixture2.

To update fixture2 of all the elements of fixtures array, you might want to use $[] instead.

Try this:

Votes.update(  { "fixtures.fixture2": { "$exists": true } },  { "$push": { "fixtures.$[].fixture2": "vote4" } },  { multi : true})

Read more about $[](positional-all) for detailed information.