Javascript mongoose预保存钩子中的异步函数不工作

Javascript mongoose预保存钩子中的异步函数不工作,javascript,node.js,mongoose,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(); }) as

在预保存挂钩中调用异步函数将返回我的密码
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

}

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

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

我不认为您可以将userSchema.pre转换为异步函数。

只是为了稍微澄清一下:

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=使用
    中的箭头功能时,可以删除该
    ,然后
  • 当使用不带回调的
    bcrypt.hash()
    时,它会返回一个承诺
  • async for hashPassword在使用时是冗余的。然后在调用

猫鼬钩子中允许异步函数。这对我有用。请注意,异步函数中不需要“next”回调参数,因为该函数是同步执行的

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

userSchema.pre('save', async function () {
  
  let user = this;

  const saltRounds = 10;

  const hashed_password = await hashPassword(user.password, saltRounds);

  user.password = hashed_password;

}); // pre save hook ends here

async hashPassword(password, saltRounds) {

  try {

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

  } catch(err){

    // error handling here

  }

  return newHash;

}

您是否了解
const password=hashPassword(user)
将是一个承诺-因为这是
async
函数(立即)返回的结果-因此,您将在承诺解决之前设置
user.password=a_Promise
并调用
next
,然后再调用
next
,以确定下一个问题,pre save hook是否理解承诺在这种情况下,我需要使用
密码。然后(user.password=password)
?这是有道理的,但我认为我需要更好地理解async/PromisesInDect,然后打电话给下一个内部人员。然后。。。您可以避免。然后通过使
userSchema.pre('save',异步函数(next){
-然后您可以
const password=wait hashPassword(user)
-从功能上讲,这与.then pattern完全相同。现在就有意义了。当然,代码中的其他错误包括:1-
async hashPassword(user){
-但该函数中从未使用过用户。2-该函数从何处获得
salthards
?3-对.hash的回调将返回hash,无论是否有错误或未读取文档,对
next
的调用在“串行预挂钩”的情况下继续“流”-所以不管返回什么都不重要