Created
February 14, 2022 16:50
-
-
Save yash-dxt/5066dac1b9afaee67a820e89baef7ed4 to your computer and use it in GitHub Desktop.
Re-using one connection everywhere - you can connect it at the start of the app and reuse the static function everywhere.
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
var config = require('../../../config'); | |
const MongoClient = require('mongodb').MongoClient; | |
const mongodbUri = process.env.MONGO_URI; | |
const logger = require('../utils/logger/index') | |
/* | |
The MDB class is a singleton class that is used to connect to the MongoDB database. The getClient() | |
method is used to get the MongoDB client. The client is cached so that it is only created once. | |
The MongoClient.connect() method is used to connect to the MongoDB database. The | |
MongoClient.connect() method returns a promise. The promise is resolved with the MongoClient object. | |
*/ | |
class MDB { | |
static async getClient() { | |
if (this.client) { | |
return this.client | |
} | |
logger.info("Cache miss - Connecting to MongoDB client now.") | |
let startTime = Date.now(); | |
this.client = await MongoClient.connect(this.url); | |
logger.info("Mongo Client time taken: " + (Date.now() - startTime).toString() + "ms"); | |
return this.client | |
} | |
} | |
MDB.url = mongodbUri; | |
module.exports = { | |
MDB | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for this !