mongo에 대한 연결이 이미 있는지 확인하고 연결을 반환하는 mongo 연결 풀 팩터 리를 만들려고합니다. 연결 풀을 만들고 연결을 반환하지 않는 경우내 모듈을 필요로하는 여러 파일이 변수를 덮어 쓰는 중임
나는 이것을 mongo를 쿼리 할 여러 파일에서 필요로하고 싶다.
var fooMongoFactory = require('../../lib/mongoFactory').init(mongodb://localhost:27017/foo);
을하고이 같은 파일에서 사용 : 각 파일은 다음과 몽고를 필요로한다
fooMongoFactory.getConnection().then(function(db) {
// do stuff
});
제가하는 데 문제는 내가 다른 여러 지정할 수 있도록하려는 것입니다 mongo 인스턴스를 파일에 저장하지만, 그렇게 할 때 두 번째 init은 첫 번째 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'라고? –
mongoFactory가 필요하면 Init가 호출됩니다. Init는 호출 스크립트가'getConnection'을 호출 할 때 사용할 db 변수를 설정합니다. 'getConnection'은 이전에 설정 한'db' 변수를 사용합니다. – Catfish
"factory"라는 이름을 지정해도 공장이되지는 않습니다. http://en.wikipedia.org/wiki/Factory_method_pattern –