我想创建一个mongo连接池工厂,检查是否已经存在一个连接到mongo并返回一个连接。如果它不创建连接池并返回连接。需要我的模块的多个文件覆盖它的变量
我希望能够从多个要查询mongo的文件中得到这个要求。每个文件应当蒙戈是这样的:
var fooMongoFactory = require('../../lib/mongoFactory').init(mongodb://localhost:27017/foo);
,然后你用它在你的文件是这样的:
fooMongoFactory.getConnection().then(function(db) {
// do stuff
});
我遇到的问题是,我希望能够以指定多个不同mongo实例在一个文件中,但是当这样做时,我的第二个init覆盖了第一个。例如:
var fooMongoFactory = require('../../lib/mongoFactory').init(mongodb://localhost:27017/foo);
var barMongoFactory = require('../../lib/mongoFactory').init(mongodb://localhost:27017/bar);
fooMongoFactory.getConnection().then(function(db) {
// querying in here is actually pointing at the mongo db "bar"
});
我如何调整我的工厂,这样我可以连接到蒙戈的多个不同的实例,以及使用在多个文件这同一个工厂,而不必每次都实例化了吗?我想过使用构造函数,但是它会在每个使用mongoFactory的文件中创建一个新的连接池。
/**
* Creates and manages the Mongo connection pool
*
* @type {exports}
*/
var Q = require('q');
var MongoClient = require('mongodb').MongoClient;
var dbPromise = null;
var db = null;
module.exports = function() {
return {
init: function init(connectionString) {
db = connectionString;
return module.exports;
},
/**
* Gets a connection to Mongo from the pool. If the pool has not been instantiated it,
* instantiates it and returns a connection. Else it just returns a connection from the pool
*
* @returns {*} - A promise object that will resolve to a mongo db object
*/
getConnection: function getConnection() {
// get a connection to mongo using the db string and return dbPromise
}
}
}();
凡/如何'init'叫什么名字? – 2014-08-28 21:18:13
在需要mongoFactory后调用Init。 Init只是设置调用脚本调用getConnection时使用的db变量。 'getConnection'使用之前设置的'db'变量。 – Catfish 2014-08-28 21:28:36
只是命名“工厂”并不能使它成为工厂。 http://en.wikipedia.org/wiki/Factory_method_pattern – 2014-08-28 21:30:45