Created
June 21, 2019 03:10
-
-
Save waptik/ffab18bad16e6d8eed70e6b90af6a3b4 to your computer and use it in GitHub Desktop.
Mongoose models import, my way
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
'use strict'; | |
const fs = require('fs'); | |
const path = require('path'); | |
const Mongoose = require('mongoose'); | |
const basename = path.basename(__filename); | |
const env = process.env.NODE_ENV || 'development'; | |
const config = require(__dirname + '/../config/config.json')[env]; | |
if (config.database.url) { | |
Mongoose.connect(config.database.url, config.database.options); | |
} else if (config.database.config.dbName) { | |
Mongoose.connect(`${config.database.protocol}://${config.database.username}:${config.database.password}@${config.database.host}:${config.database.port}`, config.database.options); | |
} else { | |
Mongoose.connect(`${config.database.protocol}://${config.database.username}:${config.database.password}@${config.database.host}:${config.database.port}/${config.database.name}`, config.database.options); | |
} | |
const db = () => { | |
const m = {}; | |
fs | |
.readdirSync(__dirname) | |
.filter(file => { | |
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); | |
}) | |
.forEach(file => { | |
const model = require(path.resolve(__dirname, file))(Mongoose); | |
m[model.modelName] = model; | |
}); | |
return m; | |
} | |
const models = db(); | |
export const mongoose = Mongoose; | |
export default models; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment