Mongoose: findOneAndUpdate pre hook not working

前端 未结 2 697
别那么骄傲
别那么骄傲 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:43

    user.pre('findOneAndUpdate', function(next){
        const user=this.getUpdate().$set;
        if(!user.password){
          next();
        }
        else{
        bcrypt.genSalt(10, function (err, salt) {
            if (err) {
              return next(err);
            }
            bcrypt.hash(user.password, salt, null, function (err, hash) {
              if (err) {
                return next(err);
              }
              user.password = hash;
               next();
            });
        });
      }
    })
    

提交回复
热议问题