How to connect multiple mongodb databases dynamically using mongoose?

There are many databases in my project, one is masterDb, and all the rest are connecting to a database based on masterDb. For example, on the verification page, the user can enter a "company identifier", this "company identifier" can be verified using masterDb, and if an identifier exists, it returns the database name for a particular company. Using the database name, I want to connect to a specific company database.

Now I can successfully log in and get the name db. Using this db name (req.headers ['x-key-db']), I can connect to a specific database. but here I put the database connection code in every api call. Is there any other 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});
		     });
	    }
	});
});
Run codeHide result
+5
source share
2 answers

You can create a module, as shown below, that will check if there is already a database connection for the database you need. If so, it will return the connection object, otherwise it will create 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];
    }       
}

, data.js data.js , API. API - :

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

@User97, , , . connections . , , : " , , , , . , , . "

0

Source: https://habr.com/ru/post/1612531/


All Articles