Last Updated: February 25, 2016
· joseym
Morton 066e

Expose Previous Values in Mongoose

I recently found myself needing to access the previous value of some mongoose schema items in my pre('save') middleware and thought others might find this solution helpful:

Define your Schema

var Model = new mongoose.Schema({
  email: {
    type: String,
    // This method holds the magic
    set: function(email) { 
      this._email = this.email;
      return email;

Middleware Usage

Model.pre('save', function (next) {
  var oldEmail = this._email;
  if(this.isModified('email')) {
    // Some condition that fires before save if the email changes ... or something.
    // Maybe we wanna fire off an email to the old address to let them know it changed 
    console.log("%s has changed their email to %s", oldEmail, this.email);

So lets say my original email was josey.morton+isOnCoderwall@domain.com and at some point I gain some common sense (likely due to being sick of typing that in all the time) and change it to something@sensible.com.

The Model would see that 1. My email changed, and 2. would know what it changed from.

The middleware could then fire off an email to the previous address and if I didn't modify the email I'd know that I've been h4x0rd and could act accordingly.

I hope this helps someone, otherwise the last 4 minutes have been wasted and my life is a failure.

Say Thanks