(假设哈希已经完成)我正在尝试通过比较输入的密码和MongoDB集合中的哈希来执行用户身份验证功能。这是my model.js中的方法(复制自bcrypt指南):
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
和我的Controller.js:
exports.check = function (req, res) {
var email = req.body['email'];
var password = req.body['password'];
PetOwner.findOne({ "email" : email}, 'email', function(err, task) {
if (err)
res.send(err);
if ( task === null ){
res.json(0); // no matching result
console.log("Email is not yet registered");
} else {
task.comparePassword(password, task.password, function(err, isMatch) { //compare password and the already-hashed password in MongoDB
if (err) throw err;
if(isMatch){
res.json(1);
console.log("Found matching password to email");
}
else{
res.json(0);
console.log("Wrong password");
}
});
}
})
};
并且当我获取check方法时,节点控制台会提示我的model.js中的cb不是函数的错误。我试过几种变通办法,但到目前为止没有一种奏效。有什么办法可以调试这个吗?
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb)
您的函数只使用一个参数,因此您不能在函数外部引用“this”的上下文,就像使用“this.password”一样。
如果添加密码作为第二个参数进行比较,如下所示:
PetOwnerSchema.methods.comparePassword = function(candidatePassword, password2, cb)
然后,您可以在函数内部进行比较。
希望有帮助