title: ExpressJS: Middleware control flow for Router.param() & Router.use()
body: <p>In my Express.js app, I have some custom validations and parameter parsing. For one of my routes, I'm expecting the obj_id to be provided as part of the route. If mongoose is unable to find an obj with that ID in the DB, then we return a 404 error. Given that I'm putting the router.param call before the router.use call, I'd expect the param validation to execute first. However, with node-inspector, I'm able to verify that the param function is not being reached before the custom middleware.</p>
  
  <p>How do I execute the param parsing before the middleware?</p>
  
  <p>Please note that this middleware is being used on multiple functions, so I don't want to add it into the router call.</p>
  
  <pre><code>router.param('obj', function(req, res, next, id){
    Obj.findOne({_id: id}, function(err, obj){
      if (err || !obj) {
        res.status(404).json({error: {message: "No obj with that ID", type: "bad_parameters.unknown_obj"}});
      } else {
        req.obj = obj;
        next();
      }
    });
  });
  
  router.use(function(req,res,next){
    ...
    //Do some validations
    ...
    if(error) return res.status(400).json(error);
    next();
  });
  ...
  //Other routes that are working well
  ...
  router.get('/:obj', obj);
  </code></pre>
  
  <p>Expected error:</p>
  
  <pre><code>404 {error: {message: "No obj with that ID", type: "bad_parameters.unknown_obj"}}
  </code></pre>
  
  <p>Actual error:</p>
  
  <pre><code>400 {error: {message: "Validation failed", type: "bad_parameters"}}
  </code></pre>
  
  <p>Thanks in advance for your help!</p>