Skip to content

Instantly share code, notes, and snippets.

@yash-dxt
Created February 14, 2022 16:50
Show Gist options
  • Save yash-dxt/5066dac1b9afaee67a820e89baef7ed4 to your computer and use it in GitHub Desktop.
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.
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
}
@OluwaDraco
Copy link

thanks for this !

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