微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Mongoose bcrypt 设置密码并异步保存

如何解决Mongoose bcrypt 设置密码并异步保存

我有一个猫鼬模式:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。