Created
May 20, 2020 04:50
-
-
Save gayanvirajith/5f9b763d93465af6c54da4307c76b13c to your computer and use it in GitHub Desktop.
Node js Mongo db connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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