0

I'm using JWT token compare function to the user password in order to authenticate user login but after the mongoose query I cant get access to the user password

exports.login = async(req, res, next) => {
    
        const {email, password} = req.body

//checking if email and password exists
        if(!email || !password){
            return next(new AppError('Provide email and password', 400))
        } 

//checking if the user exists and password is correct
    try {   
        const user = await User.find({email}).select('+password')
        if(!user || !(await user.correctPassword(password, user.password))){
            return next(new AppError('Incorrect email and password', 401))
        }
//when everything is ok send the response to the client
        const token = SignToken(user._id)
        console.log(token);
        res.status(200)
            .json({
            status: 'success',
            token
            })
        } catch(err) {
            res.status(400).json({
                status: 'fail',
                message: err
            })
        }


}

After viewing the user.password in the console it is showing undefined so my compare function is not working. I'm fairly new to JWT

1 Answers1

0

Your password is undefined as you made mistake while projecting fields by User.find({email}).select('+password').In the mongoose the select method, you can't pass "+". But if you want to skip any property you can use the "-" operator select('-password). And Also, you can't write like select("-username password"). Only the property name of the collection 'password' is enough in the select("password") method to find the password.

Look that answer might be helpful for you.

answer

Documentation Here

kumol
  • 174
  • 1
  • 9