I am trying to query mongodb in the login route for users to login to my application.
In the logic of the function, I need to query the submitted user through email param of body request. However, I am getting the error when performing such task.
const login = async(req, res) => {
const user = await User.findOne({ email: req.body.email })
const secret = process.env.secret;
if (!user) {
return res.status(400).send('the User not found!')
}
if (user && bcrypt.compareSync(req.body.password, user.passwordHash)) {
const token = jwt.sign({
userId: user.id,
isAdmin: user.isAdmin
},
secret
, { expiresIn: '1d' }
)
res.status(200).send({ user: user.email, token: token })
} else {
res.status(404).send('password Wrong');
}
}
The error output:
TypeError: Cannot read properties of undefined (reading 'email')