1

ENV:

node v12.19.0

mongo Atlas V4.2.11

mongoose V5.11.8

###############################################

I have a user Schema

user.js

const mongoose = require('mongoose');
const bcrypt   = require('bcrypt');

const userSchema = new mongoose.Schema({
    email:{
        type: String,
        required: true,
        unique: true, 
    },
    username:{
        type: String,
        required: true,
        unique: true,
    },
    password:{
        type: String,
        required: true
    },
    profileImageUrl:{
        type: String,
    }
});

userSchema.pre('save', async function(next) {
    try{
        if(!this.isModified('password')){
            return next();
        }

        let hashedPassword = await bcrypt.hash(this.password, 10);
        this.password = hashedPassword;
        return next();

    } catch(err) {
        return next(err);
    }
});

userSchema.methods.comparePassword = async function(candidatePassword){
    try{
        return await bcrypt.compare(candidatePassword, this.password);

    } catch(err){
        throw new Error(err.message);
    }
}

userSchema.set('timestamps', true);

module.exports = mongoose.model("User", userSchema);

I am checking if the password is not modified then I modify it pre saving.

and I added a method to compare password with a hashed password called comparePassword

I am trying to use the comparePassword method in another file

Auth.js


const db = require('../models');
const JWT = require("jsonwebtoken");
const CONFIGS = require('../config');

exports.signIn = async function(req, res, next){
    try{

        const user = db.User.findOne({
            email: req.body.email,
        });

        const { id, username, profileImageUrl } = user;
        const isMatch = await user.comparePassword(req.body.password) ; // here is a problem <====

        if(isMatch){
            const token = JWT.sign({
                id,
                username,
                profileImageUrl,
            }, CONFIGS.SECRET_KEY);
            return res.status(200).json({
                id,
                username,
                profileImageUrl,
                token,
            });
        }
        else{
            return next({
                status: 400,
                message: "Invalid email or password",
            });
        }
    }
    catch(err){
        return next(err);
    }
}
   

when I try to compare the passwords with the predefined method it returns this in the response

user.comparePassword is not a function

I looked at various solutions.

some said that this works for them:

userSchema.method('comparePassword' , async function(candidatePassword, next){
  // the logic
})

but it doesn't work I tried different solutions too but I am not sure what is wrong with the code.

Update 1:

I tried using statics and it doesn't work

userSchema.statics.comparePassword = async function(candidatePassword){
    try{
        return await bcrypt.compare(candidatePassword, this.password);

    } catch(err){
        throw new Error(err.message);
    }
}
Ahmed Gaafer
  • 1,603
  • 9
  • 26

2 Answers2

1

In Auth.js

 const user = db.User.findOne({
            email: req.body.email,
        });

this is wrong because we must wait for the query to finish;

it should be like this

 const user = await db.User.findOne({
            email: req.body.email,
        });
Ahmed Gaafer
  • 1,603
  • 9
  • 26
0

In My Case I was doing like this : const user = User.findById({userId})

Mistake No. 1 in Above Code - I wasn't Destructuring anything so no need of {}.

Mistake No. 2 - missing await keyword.

final code should look like this:

const user = await User.findById(userId)