mongoose get db value in pre-save hook

后端 未结 2 470
遥遥无期
遥遥无期 2021-01-04 21:21

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 = th         


        
2条回答
  •  清歌不尽
    2021-01-04 22:03

    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.

提交回复
热议问题