this.password is undefined in comparePassword method when using Bcrypt with mongoose. How to solve? this.password is undefined in comparePassword method when using Bcrypt with mongoose. How to solve? mongoose mongoose

this.password is undefined in comparePassword method when using Bcrypt with mongoose. How to solve?


you need to call the comparePassword with function.call(thisArg, arg1, arg2, ...) to bind the correct context of 'this'

so basicially instead of:

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

use:

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

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


This is a bit old, but I bump into this same problem. After spending half day, I found out why and might be applicable.

My problem is caused by the password field being declared with select: false in the schema. See the code below

var personSchema = new Schema({  first       :   {type: String, required: 'FirstNameInvalid'},  last        :   String,  email       :   {type: String, unique: true, lowercase: true, required: 'EmailInvalid'},  password    :   {type: String, select: false, required: 'PasswordInvalid'},  isLocked    :   Boolean,  isAdmin     :   Boolean});

By changing the password declaration to select: true, or even removing the whole select statement, the problem is fixed.

Note that there are some security risk involved by removing the select statement. However this will be beyond the discussion of this topic


You should try compare compareSync() instead of compare(). Hope this will work for you.

    UserCredentialSchema.methods.comparePassword = function(pwd, cb) {    var result = bcrypt.compareSync(pwd, this.password);    if (result) {           cb(null, result);    } else {           return cb(err);    }   };