Javascript 无法将密码与bcrypt compare进行比较
我正在尝试构建一个用于更改密码的节点api 用户必须键入当前密码和新密码 当bcrypt.将新的currentPassword与数据库中存储的密码进行比较时,我得到的结果总是false,无论它是错误的还是正确的Javascript 无法将密码与bcrypt compare进行比较,javascript,node.js,mongodb,mongoose,bcrypt,Javascript,Node.js,Mongodb,Mongoose,Bcrypt,我正在尝试构建一个用于更改密码的节点api 用户必须键入当前密码和新密码 当bcrypt.将新的currentPassword与数据库中存储的密码进行比较时,我得到的结果总是false,无论它是错误的还是正确的 const changePass = async (req, res, next) => { //email and password const CurrentPassword = req.body.currPassword let password1 = ''+req.bo
const changePass = async (req, res, next) => {
//email and password
const CurrentPassword = req.body.currPassword
let password1 = ''+req.body.password1
let password2 = ''+req.body.password2
const hashedPassword = await bcrypt.hash(password1, 10);
let id = "" + req.body.id
User.findById( id )
.then(user => {
bcrypt.compare(CurrentPassword, user.password, (err, data) => {
if (err) throw err
if (data) {
User.findByIdAndUpdate(id, {password : hashedPassword }, {new: false}, (err) => {
if (err) throw err
})
} else {
return res.status(401).json({ msg: "Invalid" })
}
})
})
}
如果您想学习bcrypt,我建议您访问,因为它会为您节省太多的时间 在您的情况下,我对您的密码进行了一些修改,以检查当前密码
旧密码,然后比较新密码1
和确认密码确认密码
当您对任何事情有疑问时,请随意使用console.log(“”)
,它将为您提供有关代码状态的良好视图
const changePassword = async (req, res, next) => {
let id = req.body.nid;
if(id){
console.log('Im here')
const old = req.body.old;
const newP = req.body.newP;
const newP2 = req.body.newP2;
User.findById(id,(err,user)=>{
if(user){
console.log(user)
const hash = user.password;
bcrypt.compare(old,hash,function (err,res){
if(res){
if(newP === newP2){
bcrypt.hash(newP,10, (err,hash)=>{
user.password = hash;
user.save( (err,user) =>{
if(err) return console.error(err);
console.log(user.userName +' your password has been changed');
});
});
};
};
});
}
})
}
}