如何使用猫鼬动态连接多个mongodb数据库? [英] How to connect multiple mongodb database dynamically using mongoose?

查看:77
本文介绍了如何使用猫鼬动态连接多个mongodb数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,有许多数据库,一个是masterDb,所有其他都是基于masterDb的数据库连接.例如,在验证页面中,用户可以输入公司ID",可以使用masterDb检查该公司ID",如果存在ID,则返回特定公司的数据库名称.使用数据库名称,我想连接到特定的公司数据库.

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.

现在,我可以成功登录并获取数据库名称.使用这个数据库名称(req.headers ['x-key-db']),我可以连接到特定的数据库.但是在这里,我将数据库连接代码放在每个api调用中.还有其他方法可以一次创建它,并在每个api调用中动态使用它.

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

推荐答案

您可以创建如下所示的模块,该模块将检查所需数据库的数据库连接是否已存在.如果是这样,它将返回连接对象,否则将创建一个并返回它.

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

假设您在文件上方将其命名为data.js.您只需要在具有API代码的文件中要求此模块.而且您的API代码将更改为:

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

这篇关于如何使用猫鼬动态连接多个mongodb数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆