John
John

Reputation: 565

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 ?

Upvotes: 5

Views: 2413

Answers (2)

John
John

Reputation: 565

Although the above answer is close. I got it working by doing the following, which is close but also adds the $set, which is not included above

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

Upvotes: 6

MrGabriel
MrGabriel

Reputation: 84

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

Upvotes: -1

Related Questions