There are some interesting approaches you could try here.
In the simplest case, you can simply have a function that loads an object and processes the output in an error state.
fetchResource = function(model, req, res, callback) { model.findById(req.params.id, function(err, resource) { if (err) return res.json({error: "Error fetching " + model.toString()}); else if (!playlist) return res.json({error: "Error finding the " + model.toString()}); callback(resource); }); }; app.on('/playlists/1', function(req, res) { fetchResource(Playlist, req, res, function(playlist) {
This is still quite a bit of duplication, so I can try moving it to middleware .
Routing middleware
Routes can use route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by a route, etc.
Now I have not tested this, and it is a little waved (read: pseudocode), but I think that it should serve as a worthy example.
// assuming a URL of '/playlist/5' or '/user/10/edit', etc. function loadResource(model) { return function(req, res, next) { model.findById(req.params.id, function(err, resource) { if (err) return res.json({error: "Error fetching " + model.toString()}); else if (!resource) return res.json({error: "Error finding the " + model.toString()}); req.resource = resource; next(); }); } } app.get('/playlist/:id', loadResource(Playlist), function(req, res) { var playlist = req.resource; ... }); app.get('/user/:id', loadResource(User), function(req, res) { var user = req.resource; ... });
The express source contains a pretty good example of this template , and the intermediate section in the documents (in particular, in the section "Routing middleware") describes it in detail.