在预保存 Hook 中调用异步函数会向我返回 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 返回的 promise :
hashPassword(user)
.then(password => {user.password = password
next()}
)
我不认为你可以将 userSchema.pre 变成一个异步函数。
关于javascript - Mongoose 预保存 Hook 中的异步功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48799479/