Created
December 6, 2019 11:09
-
-
Save kaungmyatlwin/6ab0321ba417d69dea9f95148c133832 to your computer and use it in GitHub Desktop.
Connect to multiple database connects with MongoDB client.
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 config = require('config'); | |
const MongoClient = require('mongodb').MongoClient; | |
const { host } = config.get('dbConfig'); | |
const mongoIp = process.env.NODE_ENV === 'production' ? host : 'localhost'; | |
class Connection { | |
static databases = {}; | |
static connectToMongo(dbName: string, options: object) { | |
const url = `mongodb://${mongoIp}/${dbName}`; | |
if (Object.keys(Connection.databases).length !== 0) { | |
return Promise.resolve(Connection.databases); | |
} | |
return MongoClient.connect(url, options) | |
.then((client: any) => { | |
Connection.databases[dbName] = client.db(dbName); | |
console.log(`Connected to ${dbName}`); | |
}).catch(err => console.error(err)); | |
} | |
} | |
Connection.databases = {}; | |
module.exports = { Connection }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment