javascript - 需要我的模块的多个文件正在覆盖它的变量

标签 javascript node.js node-mongodb-native

我正在尝试创建一个 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/

相关文章:

node.js - Node.js 中 path.normalize 和 path.resolve 的区别

node.js - 如何获取服务器ip地址以在nodejs中发送邮件

javascript - 将 agSetColumnFilter 与服务器端行模型结合使用

javascript - 在 for-in 循环中找不到值

javascript - 如何从 NodeJS 中的模块返回数组

node.js - MongoClient 和 MongoClient.connect() 方法回调中得到的客户端对象有什么区别

json - 如何查询 MongoDB 集合上的日期范围,其中 ISO 日期存储在字符串字段中?

node.js - MongoDB查询日期字段与服务器时间

javascript - NuxtJS 和 Auth 路由豁免

javascript - JS - 如何检查 2 个图像(它们的哈希值)是否相似