Skip to content

Instantly share code, notes, and snippets.

@idkjs
Forked from mikberg/connection.js
Created March 25, 2017 12:18
Show Gist options
  • Select an option

  • Save idkjs/8b1fd3b2dc84a8e2c79d59da1896a93a to your computer and use it in GitHub Desktop.

Select an option

Save idkjs/8b1fd3b2dc84a8e2c79d59da1896a93a to your computer and use it in GitHub Desktop.
MongoDB connection with async/await
import { MongoClient } from 'mongodb';
import promisify from 'es6-promisify';
let _connection;
const connect = () => {
if (!process.env.MONGO_CONNECTION_STRING) {
throw new Error(`Environment variable MONGO_CONNECTION_STRING must be set to use API.`);
}
return promisify(MongoClient.connect)(process.env.MONGO_CONNECTION_STRING);
};
/**
* 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 connection = () => {
if (!_connection) {
_connection = connect();
}
return _connection;
};
export default connection;
/**
* Returns a ready-to-use `collection` object from MongoDB.
*
* Usage:
*
* (await getCollection('users')).find().toArray().then( ... )
*/
export async function getCollection(collectionName) {
const db = await connection();
return db.collection(collectionName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment