mongoose get db value in pre-save hook

后端 未结 2 442
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 2021-01-04 22:14

    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.

    0 讨论(0)
提交回复
热议问题