Mongoose: findOneAndUpdate pre hook not working

前端 未结 2 716
别那么骄傲
别那么骄傲 2020-12-22 10:52

I\'ve searched about this issue and all the solutions that I\'ve found didn\'t actually work. I\'m currently using this function to encrypt the password before storing in th

2条回答
  •  死守一世寂寞
    2020-12-22 11:50

    I just tested this locally with:

    var result = Author.findOneAndUpdate({ _id:  }, { password: '111' }).exec()
    

    and this pre hook:

    AuthorSchema.pre('findOneAndUpdate', function(next) {
      this._update.password = 'BBB'
      next();
    });
    

    Password was saved as BBB

    Author schema has a password field which is type: String

    I am on 3.6.5

    In your bcrypt case you have also an extra next() without else which is messing you up ... should be:

    UserSchema.pre('findOneAndUpdate', function(next) {
      const update = this.getUpdate();
      if (!_.isEmpty(update.password)) {
        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(update.password, salt, (err, hash) => {
            this.getUpdate().password = hash;
            next();
          })
        })
      } else {
        next();
      }
    });
    

提交回复
热议问题