Created
June 15, 2016 06:55
-
-
Save zoozalp/a3c4f427bdd75ac20f1cf7b58bab15be to your computer and use it in GitHub Desktop.
Auto-loading mongoose models in node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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