问题描述
UserSchema.methods.setPassword = function (password) {
bcrypt.hash(password,saltRounds).then(function (hash) {
this.hash = hash;
});
};
这是我创建用户对象的方式:
router.post('/signup',function(req,res,next){
var user = new User();
user.username = req.body.user.username;
user.email = req.body.user.email;
user.setPassword(req.body.user.password);
user.save().then(function(){
return res.json({user: user.toAuthJSON()});
}).catch(next);
});
然而,它保存了没有散列密码的用户。我猜这是因为在调用 user.save 之前没有运行 bcrypt.hash 回调。我怎样才能最好地解决这个问题?
在 bcrypt 文档上说不要使用 bcrypt.hashSync,它适合这里吗?
解决方法
UserSchema.methods.setPassword = function (password) {
return new Promise((resolve,reject) => {
bcrypt.hash(password,saltRounds,(error,hash) => {
if (error) {
reject(error);
} else {
this.password = hash;
resolve(true);
}
})
})
}
然后调用
await user.setPassword(req.body.user.password);
或者可能发现错误,idk