猫鼬预保存钩子中的异步功能不起作用 [英] Async function in mongoose pre save hook not working

查看:62
本文介绍了猫鼬预保存钩子中的异步功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在预保存钩子中调用异步函数会使我返回undefined作为密码.我在这里从根本上误解了async吗?我已经在我的应用程序的其他区域成功使用了它,而且看起来工作正常……

Calling an async function in a pre save hook is returning me undefined for the password. Am I fundamentally misunderstanding async here? I've used it successfully in other areas of my app an it seems to be working fine...

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

}

推荐答案

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

I think you'd need to handle the promise returned by hashPassword:

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

我认为您无法将userSchema.pre转换为异步功能.

I don't think you can turn userSchema.pre into an async function.

这篇关于猫鼬预保存钩子中的异步功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆