我有一个 node.js 登录表单,应该验证用户名是否存在。然后应该将其与我生成的散列密码进行比较。我能够正确地将新用户注册到 mongodb 数据库。我还能够findOne() 用户。但我无法比较密码。
app.post('/login-users', async (req, res) =>{
const user = User.findOne({name: req.body.name}, function(err, user){
console.log('User Found')
})
try{
if(await bcrypt.compare(req.body.password, user.password)){
res.redirect('/')
} else{
console.log('Not Allowed')
}
} catch {
res.status(500).send()
}
})
您需要将 try catch 移至回调,因为
user
是一个未解决的承诺
app.post('/login-users', async (req, res) =>{
const user = User.findOne({name: req.body.name},async function(err, user){
console.log('User Found')
try{
if(await bcrypt.compare(req.body.password, user.password)){
res.redirect('/')
} else{
console.log('Not Allowed')
}
} catch {
res.status(500).send()
}
})
})
或者等待承诺解决
app.post('/login-users', async (req, res) =>{
const user = await User.findOne({name: req.body.name})
try{
if(await bcrypt.compare(req.body.password, user.password)){
res.redirect('/')
} else{
console.log('Not Allowed')
}
} catch {
res.status(500).send()
}
})
您也可以在猫鼬模式中使用 schema.method
userSchema.method('validatePassword', async function (password) {
const isValid = await bcrypt.compare(password, this.password)
return isValid
})
现在您可以使用
调用此方法const user = await User.findById('1234567890');
const isMatch = await user.validatePassword('password');