如何在Promise中重用mongo连接 [英] How to reuse a mongo connection with promises

查看:50
本文介绍了如何在Promise中重用mongo连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I change things around in my db connection call so that I can do 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,因此不会创建连接,所以这不是问题.例如:

My code always calls getDb so the connection does get created so that is not an issue. ex:

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

但是实际上我打了很多电话,所以寻找一种更清洁的方法.

But I actually string many of these calls around so looking for a cleaner approach.

这有效-只是想知道是否有更好的整体方法来处理这个问题.

This works - just wondering if there an overall better approach to dealing with 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示例要么只是在connect回调内部进行所有调用,要么使用诸如Express之类的框架并在启动时进行分配.

I suppose this is really just a mongo connection issue, perhaps not just promises. All the Mongo examples I see either just make all their calls inside of the connect callback or use some framework like Express and assign it on start.

推荐答案

我希望能够做到这一点

I want to be able to do this

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

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

No, that's impossible when you don't know whether the database is already connected or not. If you might need to connect at first, and that is asynchronous, then this.db must yield a promise, and you'll need to use then.

请注意,使用Bluebird可以缩短代码,并通过使用

Notice that with Bluebird you can shorten that code a bit, and avoid that verbose .then() callback by using the .call() method:

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');
};

这篇关于如何在Promise中重用mongo连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆