我想創建一個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