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
Solution 1:
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.
Solution 2:
Mongoose hooks allow async functions in them. It worked for me. Note that the "next" callback parameter is not needed in async functions as the function executes synchronously.
Here is what a correct async/await version of the code posted in the question would be. Please note that the corrections are marked in bold:
userSchema.pre('save', asyncfunction () {
let user = this;
const saltRounds = 10;
const hashed_password = awaithashPassword(user.password, saltRounds);
user.password = hashed_password;
}); // pre save hook ends hereasynchashPassword(password, saltRounds) {
try {
let newHash = await bcrypt.hash(password, saltRounds);
} catch(err){
// error handling here
}
return newHash;
}
Solution 3:
Just to clean things up a bit:
userSchema.pre('save', function(next) {
if (!this.isModified('password')) {
returnnext();
}
this.hashPassword(this.password)
.then((password) => {
this.password = password;
next();
});
});
userSchema.methods = {
hashPassword(password) {
return bcrypt.hash(password, 10);
},
}
let user = this
can be dropped when using an arrow function inthen
.- When using
bcrypt.hash()
with no callback, it returns a promise. - async for hashPassword is redundant when using .then when calling
Post a Comment for "Async Function In Mongoose Pre Save Hook Not Working"