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()
?
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.
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.
Mongoose save with an existing document will not override the same object reference. Bookmark this question. Show activity on this post.
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.
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){
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With