BCrypt哈希错误

这是我的散列密码的代码,并将已有的密码与已经发送到正文请求的密码进行比较:

//hash password of document that use this schema bcrypt.hash(user.password, null, null, function (err, hashed) { if (err) { throw err; } else { user.password = hashed; //next api next(); } }) }); userSchema.methods.comparePassword = function (password) { //refer at userSchema var user = this; //return method of bcryot library that compare two string: original password and password hashed return bcrypt.compareSync(password, user.password); }; 

但是比较这个错误信息:

 Uncaught, unspecified "error" event. (Not a valid BCrypt hash.) 

你使用null两次。 我打赌你已经把这个函数包装在了bcrypt.genSalt函数中(如果没有的话)。 您需要将第一个null写入的bcrypt salt传递给它。

这是一个完整的例子:

 userSchema.pre('save', function (next) { const SALTROUNDS = 10; // or another integer in that ballpark const user = this; if(!user.isModified('password')) { return next(); } bcrypt.genSalt(SALTROUNDS, (err, salt) => { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, (error, hash) => { if (error) { return next(error); } user.password = hash; next(); }); }); }); 

解决 !!! 进入数据库我有很多用户的密码不哈希,当我尝试login,与bcrypt.compareSync (password, user.password); 它预期已经被哈希密码。