Skip to content

Instantly share code, notes, and snippets.

@mikberg
Last active December 29, 2021 16:57
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mikberg/0a73b06533927fe717ba to your computer and use it in GitHub Desktop.
Save mikberg/0a73b06533927fe717ba 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);
}
Copy link

ghost 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
Copy link

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

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

Hope this helps.

@SyedAman
Copy link

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
Copy link

@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.

@elevenpassin
Copy link

elevenpassin commented Dec 22, 2017

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

@szkrd
Copy link

szkrd commented Dec 26, 2017

@buoyantair promisify was not available before node 8

@philipjkim
Copy link

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);
}

@ssatyamchauhan
Copy link

ssatyamchauhan commented Mar 29, 2020

And no need to make schema because this is why mongo is used for unstructured database storage.

const MongoClient = require('mongodb').MongoClient
require('dotenv').config({ path: `${__dirname}/.env` })


module.exports = async () => {

    let db;


    try {

        // Build the connection String and create the database connection
        const client = await MongoClient.connect(
            `mongodb://${process.env.DB_HOST}/${process.env.DB_NAME}`,
            {
                useNewUrlParser: true
            }
        )
        // db global variable 
        db = await Client.db(process.env.DB_NAME)
   
    }
    catch (err) {
        return console.log('Database Connection Error!', err.message)
    }
    
    return db;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment