Mongoose. updating an embedded document in an array

In mongoose official website, I found a way to delete the embedded document using _id in the array:

post.comments.id(my_id).remove(); post.save(function (err) { // embedded comment with id `my_id` removed! }); 

I am wondering how can I update, and not delete this one?

+8
mongoose
source share
2 answers

You could do

 var comment = post.comments.id(my_id); comment.author = 'Bruce Wayne'; post.save(function (err) { // emmbeded comment with author updated }); 
+11
source share

It looks like this:

  YOURSCHEMA.update( { _id: "DocumentObjectid" , "ArrayName.id":"ArrayElementId" }, { $set:{ "ArrayName.$.TheParameter":"newValue" } }, { upsert: true }, function(err){ } ); 

In this example, I am looking for an element with an id parameter, but it may be the actual _id parameter of type objectId.

Also see: MongooseJS Doc - Set Update and Related SO Question

+12
source share

All Articles