Jorge Valle

Jorge Valle

Jorge Valle is a front end developer with a particular passion for, and expertise in, JavaScript and user interfaces. Lately, he's also been diving into machine learning.

Throwing a 404 error from a Mongoose query

I'm working on a lean, simple CMS. The core of the CMS is a RESTful API, through which all the database querying is done.

The query functionality for pages is dynamic; by that I mean that when a user requests the following URL...

http://somedomain.com/a-random-page

...the CMS goes out and looks for the existence of that page at a database level. If it's not found, then the query should return a 404 error.

This is trivial to do at an Express level, when routes are clearly defined. If a route is requested, and it's not found, then we throw a 404.

A typical way of doing this in Express would be to add a catch-all route at the end of all routes. If the request doesn't match previous routes, then we throw the error.

However, if you have a dynamic URL structure, you first have to query the database through Mongoose to check if the requested content exists. Then if it doesn't exist, we return a 404.

The REST API

Here's the route that matches on dynamic content.

You could request http://somedomain.com/pages/a-made-up-page and it will match: it will just return nothing, but still a 200. This would be unsemantic.

So to correct that, we return throw a 404 from the Mongoose query. Here's the readOnePage() method on the controller.

This will effectively throw a 404 at a REST API level. Now, we need to catch this 404 in Express and tell it to render our custom 404 page if it does.

Express

In Express, the routes look like this.

Then, in the controller, we catch the 404 like this.

This allows us to throw a correct and semantic 404, and still display the view of our choice.


Books, patrons and coffee in Caffè San Marco, Trieste