How To Reuse A Mongo Connection With Promises
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.d
Solution 1:
I want to be able to do this
returnthis.db.collection('abc').findAsync()
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
.
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);
returnthis.db;
};
Job.prototype.test = function() {
returnthis.getDb().call('collection', 'abc').call('findAsync');
};
Post a Comment for "How To Reuse A Mongo Connection With Promises"