【问题标题】:How to reuse a mongo connection with promises如何重用带有承诺的 mongo 连接
【发布时间】:2015-05-01 21:18:08
【问题描述】:

如何更改我的数据库连接调用中的内容,以便我可以执行db.collection():

// Create a Mongo connection
Job.prototype.getDb = function() {
  if (!this.db)
    this.db = Mongo.connectAsync(this.options.connection);
  return this.db;
};

// I want to be able to do this
Job.prototype.test = function() {
  return this.db.collection('abc').findAsync()...
};

// Instead of this
Job.prototype.test = function() {
  return this.getDb().then(function(db) {
    return db.collection('abc').findAsync()...
  });
};

我的代码总是调用getDb,所以连接确实被创建了,所以这不是问题。例如:

this.getDb().then(test.bind(this));

但我实际上将许多这样的调用串起来,所以寻找一种更清洁的方法。

这行得通 - 只是想知道是否有更好的方法来处理这个问题。

Job.prototype.getDb = function(id) {
  var self = this;
  return new P(function(resolve, reject) {
    if (!self.db) {
      return Mongo.connectAsync(self.options.connection)
      .then(function(c) {
        self.db = c;
        debug('Got new connection');
        resolve(c);
      });
    }
    debug('Got existing connection');
    resolve(self.db);
  });
};

我想这真的只是一个 mongo 连接问题,也许不仅仅是承诺。我看到的所有 Mongo 示例要么只是在连接回调中进行所有调用,要么使用诸如 Express 之类的框架并在启动时分配它。

【问题讨论】:

  • 恐怕不行,否则你怎么知道连接是成功异步建立的?
  • @SecondRikudo - 连接在那里,因为我总是打电话给getDb - 查看我的编辑。建立连接不是问题 - 主要是清理。
  • 为了清理,bluebird提供.dispose()

标签: javascript mongodb promise bluebird


【解决方案1】:

我希望能够做到这一点

return this.db.collection('abc').findAsync()

不,当您不知道数据库是否已连接时,这是不可能的。如果您可能首先需要连接,并且这是异步的,那么this.db 必须产生一个承诺,并且您需要使用then

请注意,使用 Bluebird,您可以稍微缩短代码,并使用 .call() method 避免冗长的 .then() 回调:

Job.prototype.getDb = function() {
  if (!this.db)
    this.db = Mongo.connectAsync(this.options.connection);
  return this.db;
};
Job.prototype.test = function() {
  return this.getDb().call('collection', 'abc').call('findAsync');
};

【讨论】:

  • 如果您能提及处置器模式,也许.disposer 和适当的资源管理,那就太好了。以这种方式缓存连接有点冒险。
  • @BenjaminGruenbaum:现在你已经提到了它们 :-) 我不确定如何缓存一次性资源,或者你的意思是它们根本不应该被缓存(仅在内部蒙哥)?如果您可以编写自己的答案,这可能是值得的……
  • 我不清楚为什么我的方法不是。似乎工作得很好。我听说反模式,但坦率地说,我想进入链接 mongo 方法,这将成为它自己的事情。不是在下一个链式承诺之前创建self.db 连接吗?我没有看到这个问题,尽管它可能是一个时间问题。
  • 我基本上是想重新创建 Express/Hapi 中的流程,其中连接在启动时创建,然后用于链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2015-10-03
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
相关资源
最近更新 更多