John John - 1 year ago 106
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,

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 Source
Friend.findOneAndUpdate({_id:}, {email:, $push: { previousEmails: } 
}, {new: true}, function(err, friend){
    if (err){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download