Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose get db value in pre-save hook

I want to know what the 'clean' value of a dirty prop is in a pre-save mongoose hook like this:

UserSchema.pre('save', function(next) {
    var user = this;

    if (user.isModified('password')){
       //i want to know what the value of user.password was before it was changed
    }
    next()
}

Is it possible to look up the old value without looking it up in the db?

like image 877
mkoryak Avatar asked Aug 12 '13 17:08

mkoryak


2 Answers

By default, the old values are not stored. You would have to do is track the old data with a post init hook (a mongoose feature).

What we do is attach copy of the original document to all items pulled from MongoDB. We have this code for each schema we need to get pre-dirty data for comparison:

schema.post( 'init', function() {
    this._original = this.toObject();
} );

NodeJS is pretty efficient, and does copy on write when possible, so you don't see double the memory consumption unless you modify the entire document. Only then does _original actually consume double the memory.

like image 104
Anthony Hildoer Avatar answered Sep 24 '22 08:09

Anthony Hildoer


So in a pre-save hook, from what I can tell by reading this section of the source code, I don't think the previous value is stored anywhere. So you'll have to load the document from mongodb to get it.

However, you might want to use the virtuals mechanism instead of a pre-save hook to store the old value before changing it to the new value.

var virtual = schema.virtual('password');
virtual.set(function (v) {
  var this._oldPassword = this.password;
  return v;
});

Experiment with something along those lines and see if you can make something work suitably.

like image 28
Peter Lyons Avatar answered Sep 23 '22 08:09

Peter Lyons