I'm trying to get my head around why the if(!document) is not executed when a document is not found, but instead the app jumps straight to the catch block and returns the 500 status instead?
To clarify, there's no problem with the id sent via req.body.id, if I send a valid ID that matches a doc in the db the success block is executed. The problem is when I send an ID that doesn't match a doc the if (!document) {} block is not executed, but instead the catch block is executed.
My intention is this (if the code example is not clear enough):
if the document is not found return: return res.status(401).json({ message: 'Unauthorized.' }
If the document is found: return res.status(200).json({ message: 'Authorized.' });
If there's a db / server error: return res.status(500).json({ message: 'Internal server error.' })
Small code example below:
const login = (req, res) => {
userSchema
.findById(req.body.id)
.then((document) => {
if (!document) {
return res.status(401).json({ message: 'Unauthorized.' }).end();
}
return res.status(200).json({ message: 'Authorized.' });
})
.catch((err => return res.status(500).json({ message: 'Internal server error.' });
};
console.log(req.body.id)
right afterconst login = (req, res) => {
will tell you everything you need to know. – codemonkey