title: ExpressJS & Mongoose REST API structure: best practices?
body: <p>I'm building a REST API with the use of NodeJS (Mongoose &amp; ExpressJS). I think I have a pretty  good basic structure at the moment, but I'm wondering what the best practices are for this kind of project.</p>
  
  <p>In this basic version, everything passes through the <code>app.js</code> file. Every HTTP method is then passed to the resource that has been requested. This allows me to dynamically add resources to the API and every request will be passed along accordingly. To illustrate:</p>
  
  <pre><code>// app.js
  
  var express = require('express');
  var mongoose = require('mongoose');
  
  var app = express();
  app.use(express.bodyParser());
  
  mongoose.connect('mongodb://localhost/kittens');
  var db = mongoose.connection;
  
  var resources = [
    'kitten'
  ];
  
  var repositories = {};
  
  for (var i = 0; i &lt; resources.length; i++) {
    var resource = resources[i];
    repositories[resource] = require('./api/' + resource);
  }
  
  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', function callback() {
    console.log('Successfully connected to MongoDB.');
  
    app.get('/:resource', function (req, res) {
      res.type('application/json');
      repositories[req.params.resource].findAll(res);
    });
  
    app.get('/:resource/:id', function (req, res) {
      res.type('application/json');
      repositories[req.params.resource].findOne(req, res);
    });
  
    app.listen(process.env.PORT || 4730);
  });
  </code></pre>
  
  <p>-</p>
  
  <pre><code>// api/kitten.js
  
  var mongoose = require('mongoose');
  
  var kittenSchema = mongoose.Schema({
    name: String
  });
  
  var Kitten = mongoose.model('Kitten', kittenSchema);
  
  exports.findAll = function (res) {
    Kitten.find(function (err, kittens) {
      if (err) {
      }
      res.json(kittens);
    });
  };
  
  exports.findOne = function (req, res) {
    Kitten.findOne({ _id: req.params.id}, function (err, kitten) {
      if (err) {
      }
      res.json(kitten);
    });
  };
  </code></pre>
  
  <p>Obviously, only a couple of methods have been implemented so far. What do you guys think of this approach? Anything I could improve on?</p>
  
  <p>Also, a small side question: I have to require mongoose in every API resource file (like in <code>api\kitten.js</code>, is there a way to just globally require it in the app.js file or something?</p>
  
  <p>Any input is greatly appreciated!</p>