我正在尝试创建一个 mongo 连接池工厂,用于检查与 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"
});
如何调整我的工厂,以便可以连接到 mongo 的多个不同实例,以及在多个文件中使用同一个工厂,而不必每次都实例化它?我想过使用构造函数,但这会在使用 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
}
}
}();
最佳答案
mongodb
Node 模块已具有 built-in connection pooling当您调用 connect()
时自动使用的功能。 default max connection pool size is 5 ,但是您可以在连接 URL 中更改此值(例如 'mongodb://localhost:27017/foo?maxPoolSize=15'
)。
您还需要通过在 server config options 中设置 poolSize
来更改创建的实际连接数。小于或等于 maxPoolSize 的某个值。您可能还需要将 auto_reconnect
设置为 true。
现在您可以做的是在包含该服务器的数据库对象的主机:端口上保留一个对象。如果有人传入对象中包含主机:端口的连接字符串,则返回池。否则创建、缓存并返回新的数据库对象。
关于javascript - 需要我的模块的多个文件正在覆盖它的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25558045/