如何更改数据库连接调用中的内容,以便可以执行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示例要么只是在connect回调内进行所有调用,要么使用诸如Express之类的框架并在启动时进行分配。
最佳答案
我希望能够做到这一点
return this.db.collection('abc').findAsync()
不,当您不知道数据库是否已连接时,这是不可能的。如果您可能首先需要连接并且是异步的,那么
this.db
必须产生一个承诺,并且您将需要使用then
。请注意,使用Bluebird可以稍微缩短代码,并通过使用
.then()
method避免冗长的.call()
回调: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');
};