Skip to content

Instantly share code, notes, and snippets.

@maka-io
Last active November 6, 2017 14:18
Show Gist options
  • Save maka-io/f568689f2f027f3b537893c530f94788 to your computer and use it in GitHub Desktop.
Save maka-io/f568689f2f027f3b537893c530f94788 to your computer and use it in GitHub Desktop.
MongoDB Connection
const mgConfig = {
mgHost: 'localhost',
mgPort: 27017,
mgDb: ''
};
const mgLocalConfig = `mongodb://${mgConfig.mgHost}:${mgConfig.mgPort}/${mgConfig.mgDb}`;
export default mgLocalConfig;
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