Skip to content

Instantly share code, notes, and snippets.

@zoozalp
Created June 15, 2016 06:55
Show Gist options
  • Save zoozalp/a3c4f427bdd75ac20f1cf7b58bab15be to your computer and use it in GitHub Desktop.
Save zoozalp/a3c4f427bdd75ac20f1cf7b58bab15be to your computer and use it in GitHub Desktop.
Auto-loading mongoose models in node.js
/**
* Create an index.js file in the same directory as your models. Add this code to it. Be sure to add the necessary fs require
*/
var fs = require('fs');
// initializes all models and sources them as .model-name
fs.readdirSync(__dirname).forEach(function(file) {
if (file !== 'index.js') {
var moduleName = file.split('.')[0];
exports[moduleName] = require('./' + moduleName);
}
});
/**
* Now you can call all your models as follows:
*/
var models = require('./path/to/models');
var User = models.user;
var OtherModel = models['other-model'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment