In Express, 404 is not classified as an βerrorβ, so to speak - the argument is that 404 isn This is usually a sign that something went wrong, just the server did not find anything. It is best to explicitly send 404 to the route handler:
Posts.findOne({_id: req.params.id, deleted: false}).exec() .then(function(post) { if(!post) { res.status(404).send("Not found."); }
Or, conversely, if it seems like too much repeating code, you can always output that code to a function:
function notFound(res) { res.status(404).send("Not found."); } Posts.findOne({_id: req.params.id, deleted: false}).exec() .then(function(post) { if(!post) { notFound(res); }
I would not recommend using middleware in this situation just because I feel that it makes the code less clear - 404 is a direct result of the database code that does not find anything, so it makes sense to have a response in the route handler.
source share