如何使用promise重用mongo连接

How to reuse a mongo connection with promises

本文关键字:mongo 连接 重用 promise 何使用      更新时间:2024-07-07

如何更改数据库连接调用中的内容,以便执行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之类的框架并在启动时分配它。

我想做这个

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

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

请注意,使用Bluebird可以稍微缩短代码,并使用.call()方法避免冗长的.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');
};