我有一个应用程序,其中每个用户都有自己的子域,每个子域都有不同的mongo数据库。我试图连接到基于Referrer子域的特定数据库,首先,我检查请求来自哪个子域,然后创建动态mongo连接字符串。
let Url = 'mongodb://DB_USER:DB_PASS@DB_HOST:DB_PORT/DYNAMIC_DB_NAME';
DataAccess.setConnectionString(req, Url, domain);
在将连接实例保存到全局变量之后,我声明了一个全局数组来保存此信息。 在server.js中:
global.mongoInstances = [];
下面是我的代码,该代码首先检查是否已经建立连接,然后从全局数组提供猫鼬连接实例,但是如果请求是第一次从该子域发出的,则创建一个新连接并将实例推送到全局数组。
static setConnectionString(req, url, domain){
this.mongooseInstance = '';
let self = this;
if(domain && domain !== '') {
var inArray = false;
for (var k in global.mongoIntances) {
if (global.mongoIntances.hasOwnProperty(k)) {
if( global.mongoIntances[k].domain === domain) {
console.log('domain is aready in the array ', global.mongoIntances[k].domain, ' === request domain ', domain);
self.mongooseInstance = '';
console.log('from session to global.instance db name', global.mongoIntances[k].connections[0].name);
self.mongooseInstance = global.mongoIntances[k].instance;
inArray = true;
console.log('typeof ', global.mongoIntances[k]);
console.log('after swithching the db, new db name is ', self.mongooseInstance.connections[0].name);
return self.mongooseInstance;
}
}
}
if(!inArray) {
Mongoose.connection.close(function () {
if (global.mongoIntances.length > 0) {
console.log('before push db name is', util.inspect(global.mongoIntances[0].instance.connections[0].name, {depth: 3}));
}
self.mongooseInstance = Mongoose.connect(url);
console.log('connection url is ', url, ' and connected db is ', self.mongooseInstance.connections[0].name);
global.mongoIntances.push({domain: domain, instance: self.mongooseInstance});
if (global.mongoIntances.length > 0) {
console.log('after push db name is from array ', util.inspect(global.mongoIntances[0].instance.connections[0].name, {depth: 3}) , ' db name after push from self.mongooseInstance ', self.mongooseInstance.connections[0].name);
}
for (var k in global.mongoIntances) {
if (global.mongoIntances.hasOwnProperty(k)) {
console.log('loop global array ', global.mongoIntances[k].instance.connections[0].name , ' domian name ', global.mongoIntances[k].domain);
}
}
return self.mongooseInstance;
});
}
}
}
但是问题是,每次请求来自任何子域时,它都会用最新的连接实例替换已添加到全局数组的实例。就像请求来自demo1子域一样,数组值将为:
{domain: demo1, instance: demo1}
如果请求来自demo2子域,则数组值为:
{domain: demo1, instance: demo2}
{domain: demo2, instance: demo2}
每次将所有连接实例替换为最新的连接实例时,过去几天我都尝试过很多方法,但是我不确定这里出了什么问题,请告知是否有人知道答案。