Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect multiple mongodb database dynamically using mongoose?

In my project there are many database, one is masterDb and all other are database connect based on the masterDb. For example , in the verification page the user can enter a 'company id', this 'company id' can be checked with the masterDb and if an id exist it then return the database name for the specific company. Using the database name i want to connect to the specific company database.

Now i can successfully login and i get the db name. Using this db name (req.headers['x-key-db']) i can connect to the specific database. but here i place the database connection code inside every api call. Is there any another way to create it once and use it in every api call dynamically.

app.get('/api/student-limited/:_pageNumber/:_pageSize', function(req, res) {
		
	var db = mongoose.createConnection();
	db.open('mongodb://localhost:27017/'+req.headers['x-key-db']);
	var ClassSection = db.model('ClassSections', SectionSchema);
	var Student = db.model('Students', StudentSchema);
	
	var _pageNumber = parseInt(req.params._pageNumber), _pageSize = parseInt(req.params._pageSize);
	Student.find({}, function (err, _docs) {
		if(_docs){
			Student.find({}, null, {sort: { Name: 1} }).skip(_pageNumber > 0 ? ((_pageNumber-1)*_pageSize) : 0).limit(_pageSize).populate('_idClass').exec(function (err, docs) {
			if(err)
				res.json(err);
			else
				res.json({ "TotalCount" : _docs.length, "_Array" : docs});
		     });
	    }
	});
});
like image 880
Libu Mathew Avatar asked Oct 21 '15 06:10

Libu Mathew


People also ask

Can Mongoose connect to multiple databases?

Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.

How do I connect to multiple database dynamics in MySQL and node JS?

solution 1: create a separate server and database for each client with different port no. but i don't think this is good solution because if we have 100 client we can't maintain the code base. solution 2: create a separate database for each client and switch database connection at run time.


Video Answer


1 Answers

You can create a module like below which will check if database connection for database you need already exists. If it does, it will return the connection object otherwise it will create one and return it.

var mongoose = require('mongoose');

//Object holding all your connection strings
var connections = {};

exports.getDatabaseConnection = function(dbName) {

    if(connections[dbName]) {
        //database connection already exist. Return connection object
        return connections[dbName];
    } else {
        connections[dbName] = mongoose.createConnection('mongodb://localhost:27017/' + dbName);
        return connections[dbName];
    }       
}

Suppose you name above file as data.js. You just need to require this module in the file where you have your API code. And your API code will be changed to something like:

app.get('/api/student-limited/:_pageNumber/:_pageSize', function(req, res) {
    //Call getDatabaseConnection function we created
    var db = data.getDatabaseConnection(req.headers['x-key-db']);
    var ClassSection = db.model('ClassSections', SectionSchema);
    var Student = db.model('Students', StudentSchema);

    var _pageNumber = parseInt(req.params._pageNumber), _pageSize = parseInt(req.params._pageSize);
    Student.find({}, function (err, _docs) {
        if(_docs){
            Student.find({}, null, {sort: { Name: 1} }).skip(_pageNumber > 0 ? ((_pageNumber-1)*_pageSize) : 0).limit(_pageSize).populate('_idClass').exec(function (err, docs) {
            if(err)
                res.json(err);
            else
                res.json({ "TotalCount" : _docs.length, "_Array" : docs});
             });
        }
    });
});
like image 165
Raeesaa Avatar answered Oct 24 '22 04:10

Raeesaa