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

Viewed 1672

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()?

3 Answers
User.findOne({_id:"myid"})
.deepPopulate('relations.entity')
.exec(function(err,user) {
user.name = "my new name";
var tmp = user.relations;
 _.forEach(tmp,function(aObj){
if(search variable path == 'R'){
aObj.year = 1994;
 }
});
user.relations = tmp;
user.save(function(err,results){
console.log("results",results);
});
});
Related