Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async function in mongoose pre save hook not working

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

}
like image 459
Modermo Avatar asked Sep 12 '25 12:09

Modermo


1 Answers

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

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

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

like image 177
Robert Moskal Avatar answered Sep 15 '25 02:09

Robert Moskal