Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update sub document with "save" function in mongoose?

My questions is bit naive but I could not find an answer after searching everywhere.

I have a schema of user

name: {type:String},
relations: [{
    entity: mongoose.Schema.Types.ObjectId,
    year: {type:Number}
}]

I want to update the year of a user with relations.entity = R1

I am able to update it with an update function

var toupdate = {}
toupdate["relations.$.year"] = 1900;

User.update({'relations.entity': 'R1'},{"$set": toupdate},
    function(err,results){
    // console.log(results);
});

While this works well, I want to use .save() method as I have other fields that are already being updated above.

User.find({_id:"myid"},function(err,user){
    user.name = "my new name";

    // find the relation matching the relations.entity = "R1"

    user.save(function(err,results){
        // send my results returned
    });
})

How do I write the logic before calling save()?

like image 971
Masade Avatar asked Jul 27 '17 14:07

Masade


People also ask

What does save () do in Mongoose?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

Does update call save in Mongoose?

Working with save() When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question. Show activity on this post.


2 Answers

var year = 1900;
var entity = "R1"

User.find({_id:"myid"},function(err,user){
    user.name = "my new name";
    if ( user.relations && Object.prototype.toString.call( user.relations ) === '[object Array]' ) {
       user.relations.forEach( (relation, index , relations) => { 
          if(relation.entity === entity  ) {
             relations[index].year = year;
          }
       })
    }
    // find the relation matching the relations.entity = "R1"

    user.save(function(err,results){
        // send my results returned
    });
})

For multi relation update you can change entity to array and using indexOf to update the year.

like image 186
Pankaj Jatav Avatar answered Oct 10 '22 11:10

Pankaj Jatav


User.findOne({_id:"myid"},function(err,user){
  user.name = "my new name";
  var tmp = user.relations;
  _.forEach(tmp,function(aObj){
    if(aObj.entity == 'R'){
      aObj.year = 1900;
    }
  });
  user.relations = tmp;
  user.save(function(err,results){
  });
});
like image 40
Dinesh Avatar answered Oct 10 '22 13:10

Dinesh