Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose. updating embedded document in array

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?

like image 411
Erik Avatar asked Jan 21 '12 19:01

Erik


People also ask

How do I update an embedded file in MongoDB?

Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.

How can I update multiple documents in Mongoose?

$in -The $in operator selects the documents where the value of a field equals any value in the specified array. 1) {multi:true} to update Multiple documents in mongoose . 2)use update query to update Multiple documents ,If you are using findOneAndUpdate query only one record will be updated.

How do I update my Mongoose?

The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.

Can we overwrite Mongoose default ID with own id?

You can also overwrite Mongoose's default _id with your own _id . Just be careful: Mongoose will refuse to save a document that doesn't have an _id , so you're responsible for setting _id if you define your own _id path.


2 Answers

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

like image 53
guiomie Avatar answered Sep 18 '22 21:09

guiomie


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!');
});
like image 20
Kyle Zinter Avatar answered Sep 16 '22 21:09

Kyle Zinter