Created
February 6, 2018 18:45
-
-
Save email2vimalraj/7461453cca4542a979497c0c0da831e1 to your computer and use it in GitHub Desktop.
Simple mongoose db
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 { Mongoose } = require('mongoose'); | |
let connection = null; | |
const connectToDB = async () => { | |
const mongoose = new Mongoose(); | |
mongoose.Promise = global.Promise; | |
let mongoUserCredentials = ''; | |
if (process.env.MONGO_USER && process.env.MONGO_PASSWORD) { | |
mongoUserCredentials = `${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@`; | |
} | |
const MONGO_URL = process.env.MONGO_URL || 'localhost:27017'; | |
const DB_NAME = process.env.MONGO_DB_NAME || 'sample-db'; | |
const MONGO_CONNECTION_STRING = `mongodb://${mongoUserCredentials}${MONGO_URL}/${DB_NAME}`; | |
await mongoose.connect(MONGO_CONNECTION_STRING); | |
connection = mongoose; | |
}; | |
const getDB = () => { | |
if (!connection) { | |
throw new Error('Call connectToDB first'); | |
} | |
return connection; | |
}; | |
module.exports = { | |
connectToDB, | |
getDB, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment