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?

royhowie
  • 11,075
  • 14
  • 50
  • 67
Erik
  • 14,060
  • 49
  • 132
  • 218

3 Answers3

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

Community
  • 1
  • 1
guiomie
  • 4,988
  • 6
  • 37
  • 67
11

You could do

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

post.save(function (err) {
    // emmbeded comment with author updated     
});
Cris-O
  • 4,989
  • 3
  • 17
  • 11
  • 4
    Save doesn't seem to fire when I update embedded documents - and marking it changed doesn't invalidate it either. – Kevin Wang Sep 11 '13 at 03:51
1

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!');
});