mongoose pre save hook中的异步函数无效

时间:2018-02-15 03:17:53

标签: javascript node.js mongoose

在预保存挂钩中调用异步函数会返回undefined密码。我在这里从根本上误解了async吗?我已经在我的应用程序的其他方面成功使用它,它似乎工作正常......

userSchema.pre('save', function (next) {

  let user = this

  const saltRounds = 10;

  const password = hashPassword(user)
  user.password = password;

  next();

})


async hashPassword(user) {

    let newHash = await bcrypt.hash(password, saltRounds, function(err, hash) {

    if (err) {
      console.log(err)
    }

    return hash    

  });

  return newHash

}

3 个答案:

答案 0 :(得分:3)

我认为您需要处理hashPassword返回的承诺:

 hashPassword(user)
 .then(password => {user.password = password
                    next()}
 )

我认为你不能将userSchema.pre变成异步函数。

答案 1 :(得分:0)

只是为了清理一下:

userSchema.pre('save', function(next) {
    if (!this.isModified('password')) {
        return next();
    }

    this.hashPassword(this.password)
        .then((password) => {
            this.password = password;
            next();
        });
});

userSchema.methods = {
    hashPassword(password) {
        return bcrypt.hash(password, 10);
    },
}
    let user = this中使用箭头功能时,可以删除
  • then
  • 使用bcrypt.hash()时没有回调,它会返回一个承诺。
  • 在使用.then调用时,
  • hashPassword的异步是多余的

答案 2 :(得分:0)

猫鼬挂钩允许使用异步功能。它为我工作。请注意,异步函数不需要“ next”回调参数,因为该函数是同步执行的。

这是问题中发布的代码的正确异步/等待版本。请注意,更正用粗体标记:

userSchema.pre('save', async function(){

让用户=这个;

const saltRounds = 10;

const hashed _ 密码= 等待 hashPassword(用户。密码 saltRounds );

user.password = hashed_pa​​ssword;

}); //预保存钩子在此处结束


异步hashPassword( password,saltRounds ){

尝试{

let newHash =等待bcrypt.hash(password,saltRounds);

} catch(err){

//错误处理在这里

}

返回newHash;

}