I have created a static method in my schema that defines the User document structure in my MongoDB database. This method, .findByCredentials()
, is used to verify if a user-provided email and password match an existing user and hashed password in the database. If the user cannot be found by the method, an error is thrown. Similarly, if a user is found but the bcrypt.compare()
function returns false
(indicating a mismatched password), an error is thrown. I am implementing this using Mongoose and Express.
The issue I am encountering is that the error messages I have defined are not being passed to my Express route, although the .catch()
statement is triggered when incorrect credentials are passed to the route (and subsequently to the middleware function). While I can update the res.status()
and obtain a console log from the .catch()
statement, I am unable to display the errors I set in the middleware. Please pardon my vague explanation, as I am still learning about backend development and server operations.
I have attempted to set the message
property on the Error object like so:
throw new Error({ message: "Some message goes here" })
and then adjusted the .catch()
in my Express route as follows:
.catch(error) {
res.status(400)
res.send(error.message)
}
Currently, the Express route has a console log that triggers in the presence of an error, and I can see it in the console. However, when I check Postman, the res.send(error)
displays an empty object. While my Express application is configured to parse JSON (app.use(express.json())
), I have also tried various methods to parse the error without success.
Express Route:
router.post('/users/login', async (req, res) => {
const _email = req.body.email
const _password = req.body.password
try {
const user = await User.findByCredentials(_email, _password)
res.send(user)
} catch (error) {
res.status(400)
if (error) {
console.log("THERE IS AN ERROR") // THIS CONSOLE LOG TRIGGERS
res.send(error)
}
}
})
Middleware (defined in a typical User schema)
serSchema.statics.findByCredentials = async function (email, password) {
const user = await User.findOne({ email })
if (!user) {
throw new Error({ message: 'Unable to log in. Please check your credentials and try again.' })
}
const isMatch = await bcrypt.compare(password, user.password)
if (!isMatch) {
throw new Error({ message: 'Unable to log in. Please check your credentials and try again.' })
}
return user
}
The main goal is to access the error messages I defined in the static method. While this is not critical for the application's functionality, it is a learning point for me. As far as I can tell, the middleware is functioning as expected—returning a user document from the database when the provided email address and password match what is stored. My current focus is on retrieving error messages to identify incorrect credentials, but I acknowledge the security implications this might pose in a real-world application.