-
-
Save dionimercado/dd30d3ca4da7dc9830c05de0dd52d5fa 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