Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
@makmm

This comment has been minimized.

Copy link

commented Aug 7, 2017

Hey, I found this and it will probably help me a bunch!
But, with node v8, it errors at 'import'....
Do I need to use another version of node? A module?
If I need to do some babel-related stuff, I would probably prefer a babel-less approach.
Thanks! :)

@Fire-Brand

This comment has been minimized.

Copy link

commented Aug 9, 2017

@makmm - import isn't in node yet, but i believe you can do:

const { MongoClient } = require('mongodb');

Hope this helps.

@SyedAman

This comment has been minimized.

Copy link

commented Aug 13, 2017

Does connecting with MongoClient normally not return a promise? Is this why I'm getting mPromise deprecation warnings when using Mongoose?

Thank you for show us how to do this! I'm trying to figure out if I should use Promisify when using Mongoose as well

@qodesmith

This comment has been minimized.

Copy link

commented Aug 20, 2017

@SyedAman If you're using the connect method from MongoClient, it always returns a promise:

 const mongo = MongoClient.connect(url); // this is a promise

You can see this in the Mongo docs here.

@buoyantair

This comment has been minimized.

Copy link

commented Dec 22, 2017

Why did you not use promisify from the util library of nodejs?

@szkrd

This comment has been minimized.

Copy link

commented Dec 26, 2017

@buoyantair promisify was not available before node 8

@philipjkim

This comment has been minimized.

Copy link

commented Jun 4, 2018

This really helped. BTW I had a following error on L38 (getCollection):

TypeError: db.collection is not a function

I used MONGO_CONNECTION_STRING value with database name at the end of URI, but didn't work.

So I edited a little like followings and it worked:

export async function getCollection(collectionName) {
  const db = (await connection()).db(YOUR_DATABASE_NAME);
  return db.collection(collectionName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.