Skip to content

Instantly share code, notes, and snippets.

@peZhmanParsaee
Created May 30, 2020 14:06
Show Gist options
  • Save peZhmanParsaee/e7e25a17dd36a70bf6289187cab2c994 to your computer and use it in GitHub Desktop.
Save peZhmanParsaee/e7e25a17dd36a70bf6289187cab2c994 to your computer and use it in GitHub Desktop.
MongoDB singleton connection in Node.js
const MongoClient = require("mongodb").MongoClient;
const config = require("./config");
module.exports = (function () {
let connectionInstance;
let db;
function getInstance() {
return new Promise(function (resolve, reject) {
if (connectionInstance) {
return resolve(connectionInstance);
}
const options = {
useNewUrlParser: true
};
MongoClient.connect(config.db.url, options, function (err, client) {
if (err) {
return reject(err);
}
connectionInstance = client;
db = client.db(config.db.name);
return resolve(connectionInstance);
});
});
}
function getDb() {
if (!db) {
throw new Error("db object is not initialized!");
}
return db;
}
return {
getInstance,
getDb
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment