Created
February 4, 2018 10:12
-
-
Save lucasscariot/9e9c76de8678406c0fd823d98802dd18 to your computer and use it in GitHub Desktop.
Mongoose index models connections like Sequelize Raw
This file contains 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
const fs = require('fs') | |
const path = require('path') | |
const mongoose = require('mongoose') | |
const basename = path.basename(module.filename) | |
const db = {} | |
mongoose.connect(process.env.MONGODB_URI) | |
fs | |
.readdirSync(__dirname) | |
.filter(file => | |
(file.indexOf('.') !== 0) && | |
(file !== basename) && | |
(file.slice(-3) === '.js')) | |
.forEach((filename) => { | |
const filepath = path.join(__dirname, filename) | |
const imported = (require(filepath).default) ? | |
require(filepath).default : require(filepath) | |
if (typeof imported.modelName !== 'undefined') { | |
db[imported.modelName] = imported | |
} | |
}) | |
Object.keys(db).forEach((modelName) => { | |
if (db[modelName].associate) { | |
db[modelName].associate(db) | |
} | |
}) | |
module.exports = db |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment