简体   繁体   English

Mongoose bcrypt 设置密码并异步保存

[英]Mongoose bcrypt set password and saving asynchronously

I have a mongoose schema:我有一个 mongoose 架构:

UserSchema.methods.setPassword = function (password) {
bcrypt.hash(password, saltRounds).then(function (hash) {
    this.hash = hash;
    }); 
};

and here is how I create the user object:以下是我创建用户 object 的方法:

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);
});

However, it saves the user without the hashed password.但是,它可以在没有散列密码的情况下保存用户。 I guess it's because the bcrypt.hash callback didn't run before user.save is called.我猜这是因为在调用 user.save 之前没有运行 bcrypt.hash 回调。 How can I best resolve this issue?我怎样才能最好地解决这个问题?

On the bcrypt doc it says not to use bcrypt.hashSync, would it be an appropriate here?在 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);
        }
    })
  })
}

and then call然后打电话

await user.setPassword(req.body.user.password);

or maybe catch the error, idk或者可能会发现错误,idk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM