10

In the a official mongoose site I've found how can I remove embedded document by _id in array:

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

I'm interested how can I update instead removing this one?

3 Answers 3

17

It shoud look something like this:

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

        }
    );

In this exemple I'm searching an element with an id parameter, but it could be the actual _id parameter of type objectId.

Also see: MongooseJS Doc - Updating Set and Similar SO question

Sign up to request clarification or add additional context in comments.

Comments

11

You could do

var comment = post.comments.id(my_id);
comment.author = 'Bruce Wayne';

post.save(function (err) {
    // emmbeded comment with author updated     
});

1 Comment

Save doesn't seem to fire when I update embedded documents - and marking it changed doesn't invalidate it either.
0

Update to latest docs on dealing with sub documents in Mongoose. http://mongoosejs.com/docs/subdocs.html

var Parent = mongoose.model('Parent');
var parent = new Parent;

// create a comment
parent.children.push({ name: 'Liesl' });
var subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true

parent.save(function (err) {
  if (err) return handleError(err)
  console.log('Success!');
});

1 Comment

This doesnt appear to update the embedded document.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.