在Mongoose方法上使用bcrypt时出现UnhandledPromiseRejectionWarning

问题描述

尝试实施重置密码功能,并在执行此操作时始终出现UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined,string错误。我已经在其他项目中使用过此代码,并且可以完美地工作,但是由于某些原因,我似乎无法弄清楚为什么它会不断弹出,或者下面的代码可能有什么问题。

方法

UserSchema.methods.hashPassword = () => {
  return new Promise((resolve,reject) => {
    bcrypt.genSalt(10,(err1,salt) => {
      if (err1) {
        reject(err1);
      }
      bcrypt.hash(this.password,salt,(err2,hash) => { // <-- it appears to happen on this line at ".hash"
        if (err2) {
          reject(err2);
        }
        this.password = hash;
        resolve(hash);
      });
    });
  });
};

路线:

const resetPassword = async (req,res) => {

      // Update User
      const { password } = req.body;
      user.password = password;
      user.passwordResetToken = '';
      user.passwordResetExpires = moment().utcOffset(0);

      user.hashPassword().then(() => { <---- Happens here
        // Save Updated User to the Database
        user.save((error) => {
          if (error) {
            return res.status(500).json({
              success: false,message: 'An unexpected error occurred.',});
          }

          // Send Email Confirming Password Change to the User
          
        });
      });
    });
  });
};

解决方法

bcrypt也不适合我,但bcryptjs可以 删除bcrypt后尝试导入“ bcryptjs”,

您可以在这里https://www.npmjs.com/package/bcryptjs

然后将其导入到您的文件中,然后重试