mongoose: Method is not a function

Hi,

I have this method in my model:

// Compare password
UserSchema.methods.comparePassword = function(candidatePassword){
    return bcrypt.compareSync(candidatePassword, this.password);
};

let User = mongoose.model('User', UserSchema);
export default User;

When i try call this method, i receive this error:

events.js:160
      throw er; // Unhandled 'error' event
      ^

TypeError: users_1.default.comparePassword is not a function

Where is the error here ?

Please mention your node.js, mongoose and MongoDB version. Node: v6.3.10 MongoDB: v3.2.13 Mongoose: v4.9.9

Thanks,

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

solved it using await on fetching user. let user = await UserModel.findOne({ email }); Its design flaw on my part

comparePassword is a method, not a static. You’re calling it off the User model but you need to call it off the user instance:

if (!user.comparePassword(password)) return done(null, err);

you should use the asynchronous option with promises or callbacks:

With promises:

// Load hash from your password DB. 
bcrypt.compare(myPlaintextPassword, hash).then(function(res) {
    // res == true 
});

with callbacks:

// Load hash from your password DB. 
bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
    // res == true 
});