Last active
November 6, 2017 14:18
-
-
Save maka-io/f568689f2f027f3b537893c530f94788 to your computer and use it in GitHub Desktop.
MongoDB Connection
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 mgConfig = { | |
mgHost: 'localhost', | |
mgPort: 27017, | |
mgDb: '' | |
}; | |
const mgLocalConfig = `mongodb://${mgConfig.mgHost}:${mgConfig.mgPort}/${mgConfig.mgDb}`; | |
export default mgLocalConfig; |
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
import { MongoClient } from 'mongodb'; | |
import promisify from 'es6-promisify'; | |
import colors from 'colors'; | |
import mgLocalConfig from './mg-config.js'; | |
let _connection; | |
const connect = () => { | |
return promisify(MongoClient.connect)(process.env.MONGO_CONNECTION_STRING || mgLocalConfig); | |
}; | |
/** | |
* Returns a promise of a `db` object. Subsequent calls to this function returns | |
* the **same** promise, so it can be called any number of times without setting | |
* up a new connection every time. | |
*/ | |
const mgConn = () => { | |
if (!_connection) { | |
console.log(`[+] Enabling MongoDB client ...`.green); | |
_connection = connect(); | |
} | |
return _connection; | |
}; | |
export default mgConn; | |
/** | |
* Returns a ready-to-use `collection` object from MongoDB. | |
* | |
* Usage: | |
* | |
* (await mongoCollection('users')).find().toArray().then( ... ) | |
*/ | |
export async function mgCollection(collectionName) { | |
const db = await mgConn(); | |
return db.collection(collectionName); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment