Skip to content

Instantly share code, notes, and snippets.

@lucasscariot
Created February 4, 2018 10:12
Show Gist options
  • Save lucasscariot/9e9c76de8678406c0fd823d98802dd18 to your computer and use it in GitHub Desktop.
Save lucasscariot/9e9c76de8678406c0fd823d98802dd18 to your computer and use it in GitHub Desktop.
Mongoose index models connections like Sequelize Raw
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