Skip to content

Instantly share code, notes, and snippets.

@ImtiazChowdhury
Last active December 1, 2021 13:28
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 ImtiazChowdhury/964e2040c77de64ba666e20a36d55de4 to your computer and use it in GitHub Desktop.
Save ImtiazChowdhury/964e2040c77de64ba666e20a36d55de4 to your computer and use it in GitHub Desktop.
Node.JS MongoDB client connection
"use strict";
/**
Usage:
const client = require("/path/to/this/file")
async function someFunction(){
//...
const db = await client.db();
db.collection("user").findOne({});
db.close();
// ...
}
**/
const fs = require("fs");
const mongoDB = require("mongodb");
const config = require("/path/to/config") /*change this to a config file which has a db name as "db" property */
const url = "mongodb://127.0.0.1:27017"; /*change this to mongo server uri*/
const WRITE_ERR_LOGS_TO_FILE = true; /*no log file if false */
class Client {
constructor() {
//copy all props of mongodb
Object.assign(this, mongoDB);
this._client = null;
this._connect = this._connect.bind(this);
this.dbName = config.db;
this.getDB = this.getDB.bind(this);
}
async _connect() {
if (!this._client) {
try {
this._client = await mongoDB.MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
return this._client; //as of mongodb 4.0.13 MongoClient.connect return client object
} catch (err) {
if (WRITE_ERR_LOGS_TO_FILE) {
fs.appendFile("./mongoError.log", JSON.stringify(err, null, 4), (fileWriteError) => {
if (fileWriteError) console.log(fileWriteError) // :| what else to do ? lol :p
});
}
console.log(err);
throw err;
}
}
return this._client;
}
async getClient() {
//return client if already connected
if (this._client) return this._client;
//or create new client and return
return await this._connect();
}
async getDB(dbName = this.dbName) {
if (!this._client) await this._connect();
let db = this._client.db(dbName);
return db;
}
async getCollection(collectionName, dbName = this.dbName) {
if (!this._client) await this._connect();
let collection = this._client.db(dbName).collection(collectionName);
return collection;
}
async closeClient() {
if (this._client) {
await this._client.close();
this._client = null;
}
}
}
module.exports = new Client();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment