Skip to content

Instantly share code, notes, and snippets.

@gayanvirajith
Created May 20, 2020 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gayanvirajith/5f9b763d93465af6c54da4307c76b13c to your computer and use it in GitHub Desktop.
Save gayanvirajith/5f9b763d93465af6c54da4307c76b13c to your computer and use it in GitHub Desktop.
Node js Mongo db connection
# Credit: https://medium.com/swlh/how-to-connect-to-mongodb-using-a-promise-on-node-js-59dd6c4d44a7
const config = require('config');
const MongoClient = require('mongodb').MongoClient;
var _connection;
var _db;
const closeConnection = () => {
_connection.close();
}
/**
* Connects to mongodb using config/config.js
* @returns Promise<Db> mongo Db instance
*/
const getDbConnection = async () => {
if (_db) {
return _db;
}
console.log('trying to connect');
const mongoClient = new MongoClient(config.mongodb.url, { useNewUrlParser: true });
_connection = await mongoClient.connect();
_db = _connection.db(config.mongodb.databaseName);
return _db;
}
module.exports = { getDbConnection, closeConnection };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment