How to connect multiple mongodb database dynamical

2020-06-16 09:44发布

问题:

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});
		     });
	    }
	});
});

回答1:

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});
             });
        }
    });
});