当将 Bcrypt 与 mongoose 一起使用时,comparePassword 方法中 this.password 未定义。怎么解决?

Juh*_* S. 5 undefined bcrypt mongoose node.js

从 Mongo DB 获取记录后,调用comparePassword 方法来比较用户输入的密码和数据库中存储的密码。打印记录时,会显示所有数据,而在comparePassword 内部,this.password 未定义。

    User.findOne ({ username : req.body.username },
      function(err, user) {
  if (err) throw err;
console.log(user);
 user.comparePassword(req.body.password, function(err, isMatch) {
    if (err) throw err;
    console.log('Password Match:', isMatch); 
});});
Run Code Online (Sandbox Code Playgroud)

方法:

    UserCredentialSchema.methods.comparePassword = function(pwd, cb) {
bcrypt.compare(pwd, this.password, function(err, isMatch) {
    console.log(this.password);
    if (err) return cb(err);
    cb(null, isMatch);
});};
Run Code Online (Sandbox Code Playgroud)

r00*_*dev -1

您需要使用 function.call(thisArg, arg1, arg2, ...) 调用comparePassword 来绑定“this”的正确上下文

所以基本上代替:

user.comparePassword(req.body.password, function(err, isMatch) {
    if (err) throw err;
    console.log('Password Match:', isMatch); 
});
Run Code Online (Sandbox Code Playgroud)

使用:

user.comparePassword.call(this, req.body.password, function(err, isMatch) {
    if (err) throw err;
    console.log('Password Match:', isMatch); 
});
Run Code Online (Sandbox Code Playgroud)

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call