【问题标题】:Mongoose bcrypt set password and saving asynchronouslyMongoose bcrypt 设置密码并异步保存
【发布时间】:2021-06-15 15:38:09
【问题描述】:

我有一个猫鼬模式:

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,在这里合适吗?

【问题讨论】:

  • 尝试在 then 中放一个箭头函数,这样这将引用 mongos 架构

标签: javascript node.js mongoose async-await bcrypt


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2019-06-28
    • 2014-10-24
    • 2023-03-19
    • 2019-09-21
    • 1970-01-01
    相关资源
    最近更新 更多