Automatic model loading for Mongoose ODM

In order to automatically load/use Mongoose ODM models just create index.js file in a directory with your models (for example lib/models) and put there this code:

let fs   = require('fs'),
    path = require('path');

let db = {}

fs.readdirSync(__dirname).filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== 'index.js')
}).forEach(function(file) {
    let name = path.parse(file).name;

    name = name.charAt(0).toUpperCase() + name.slice(1);

    db[name] = require(path.join(__dirname, file))
})

module.exports = db

The just use it like this:

const _MODELS = require('lib/models');

_MODELS.User.find()
_MODELS.Article.find()
Fork me on GitHub