John John - 5 months ago 13
Node.js Question

How to update an object and push into an array at the same time in mongoose

I have a Schema as below

var FriendsSchema = new Schema({
email: {
type: String
}
firstName: String,
lastName: String,
previousEmails:[{
email:{
type:String
}
}],
createdDate:{
type:Date,
default:Date.now
},
updatedDate:{
type:Date,
default:Date.now
}
});


What I am trying to do is, that on an update, if the 'email' changes, I would like to update the 'email' field to the new value being passed in, and push the current 'email' value into the 'previousEmails' array.

I am able to accomplish this in two steps as follows:
1) Update the object by id, and set all fields except the array 'previousEmails'
2) If the 'email' field of the object was changed, push the old value into 'previousEmails' array.

My question is, is it possible to do this in one step ? So I have the $push and $set as party of my query ?

Answer
Friend.findOneAndUpdate({_id: req.body.id}, {email: req.body.email, $push: { previousEmails: this.email } 
}, {new: true}, function(err, friend){
    if (err){
        console.log(err); 
    } 
});
Comments