I want my pre('save') mongoose function to operate only once

后端 未结 1 1752
广开言路
广开言路 2021-01-27 20:20

I do not know if the exact request in title is possible, but if not; i would really appreciate an alternate solution.

I have this pre save method of mongoose

<         


        
相关标签:
1条回答
  • 2021-01-27 21:17

    You could use isModified method on your 'password' field.

    I use it in this way, only run bcrypt if the password property was changed:

    UserSchema.pre('save', function (next) {
      var user = this;
    
      if (user.isModified('password')) {
        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(user.password, salt, (err, hash) => {
            user.password = hash;
            next();
          });
        });
      } else {
        next();
      }
    });
    
    0 讨论(0)
提交回复
热议问题