1

I want to connect to different database(MongoDB) based on the Redis configuration. So i have to read the redis database and have to make database connection(MongoDb). Also have to make sure that its singleton.

What i have tried is

dbConenction.js:

var MongoClient = require('mongodb').MongoClient;
var db;
var connectDatabase = function connectDatabase(url)  {
    if (!db) {

        //var connectionString  = "mongodb://"+userName + ":" + password + "@" + host+ "27017/" +db;
        console.log(url); 
        //db = mysql.createConnection(settings);
        //MongoClient.connect(connectionString)

        MongoClient.connect(url, function(err, db){
            if(!err) {
                console.log("ddddddddd");
                console.log(db);
                console.log('Database is connected!');
                db = db;                
            } else {
                console.log('Error connecting database!');                
            }
        });
    }
}

module.exports.connectDatabase = connectDatabase;
module.exports.db = db;

In app.js:

var url = "mongodb://127.0.0.1:27017/pal";-----> this need to be read from Redis Database.
global.db = require('./db/dbConnection').connectDatabase(url)

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var configureRouter = require('./routes/configure');
var validationRouter = require('./routes/datavalidations');

in my routes.js

I printed the following

console.log("db");
console.log(db);

Its Undefined i know this is because before connecting to DB the Routes are loaded(asynchronous). So please suggest me how can i architect this so that its singleton. Thanks in advance.

Subburaj
  • 5,114
  • 10
  • 44
  • 87

1 Answers1

0

I don't think you need to use singleton here, b/c you need different connections. But if the question is about how to manage async in mongo, I'd promisify mongo, i.e.:

const Promise = require("bluebird");
const MongoDB = require("mongodb");
const { MongoClient } = MongoDB;

Promise.promisifyAll(MongoDB);

module.exports.connectDatabase = (url) => MongoClient.connect(url);

And next use it in the something like this way:

const c = require('./connectSingleton');

c.connectDatabase('mongodb://127.0.0.1:27017/pal')
.then( db => {
    //your db operations
    db.close();
})
.catch( err => {
    //exception handler here
});

There are actually some other libraries to manage async in mongo, like mongodb-promisified.

Also, you can take a look into already answered question about promisifying mongo

Hope it helps.

Alejandro
  • 5,834
  • 1
  • 19
  • 36