Create a gist now

Instantly share code, notes, and snippets.

Express middleware to find an item and decide if go next
* A middleware to check if id exists in collection
* app.get('/resources/:id/', exist('id', collection), function(req, res){...}}
* @param {String} id the parameter name of item id in req object
* @param {Model} collection the collection model
* @return {Function} the middleware
function exist(id, collection) {
return function (req, res, next) {
collection.findById(req.params[id]).exec(function (err, item) {
if (err) {
return res.send(500, 'Something wrong!');
if (!item) {
return res.send(404, 'item ' + req.params[id] + ' not found');
req[req.params[id]] = item;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment