title: how to access db from node.js middleware
body: <p>I want to verify that a user has a role which allows him/her to use an endpoint in my API. Usually I would go about doing so by taking the userId sent as part of a JWT and do a lookup on the DB to see what the user's role is. It would happen inside an API call and would look something like this:</p>
  
  <pre><code>var userId = getUserIdFromJwt();
  
  app.models.User.findOne({_id: userId}, function (err, user) {
      ...check if user is in role...
  });
  </code></pre>
  
  <p>Now I want to try and move that code to a piece of middleware, which would look like this:</p>
  
  <pre><code>exports.isUserInRole = function(app, allowableRoles) {
      var userId = getUserIdFromJwt();
  
      app.models.User.findOne({_id: userId}, function (error, user) {
          if (error) {
              return res.status(500).json(error);
          }
  
          return function (req, res, next) {
              if(_.includes(allowableRoles, user.Role)) {
                  next();
              } else {
                  return res.status(401).json({"error": "User not in role"});
              }
          }
      });
  };
  </code></pre>
  
  <p>The middleware would be implemented like this:</p>
  
  <pre><code>const allowableRoles = ['admin', 'implementor'];
  app.get('/getStuff/', isUserInRole(app, allowableRoles), function (req, res) {
     ... do stuff if user is in role ...
  });
  </code></pre>
  
  <p>At this point I am running into a problem where the <code>app.models.User</code> value  is always <code>undefined</code>.</p>
  
  <p>I do not understand why <code>app.models.User</code> is undefined at this point as I can access it within the anonymous function inside the get call.</p>
  
  <p>How would I go about about access the DB from within my middleware if I cannot send it <code>app.models.User</code>?</p>
  
  <p>For reference, I am using Mongoose and exposing it to my app in the server.js from which I access the a MongoDB db.</p>