Open bodokaiser opened 10 years ago
How do we handle multiple connections?
over some mongodb connection pool or you just take the returned db instance and handle it your self
Monk is so close to being able to do this out of the box. While not perfect, I've been able to wrap monk in order to cache the connection.
var monk = require('monk');
function MongoConnector() {
this.collections = {};
this._queue = [];
this.on('open', function (db) {
this._queue.forEach(function (cb) {
cb(db);
});
});
}
MongoConnector.prototype = Object.create(monk.prototype);
MongoConnector.prototype.executeWhenOpened = function() {
switch (this._state) {
case 'open':
return Promise.resolve(this._db);
case 'opening':
case 'closed':
default:
return new Promise(resolve => {
this._queue.push(resolve);
});
}
};
var connector = module.exports = new MongoConnector;
module.exports.connect = (uri, opts) => {
return new Promise(resolve => {
connector.open(uri, opts, resolve);
});
};
module.exports.disconnect = (force) => {
return new Promise(resolve => {
connector.close(force, resolve);
});
};
Now, I'm able to initialize the connection by requiring my file:
var connector = require('./path/to/connector/');
connector.connect('mongodb://localhost/mydb');
And of course, in some other file:
var connector = require('./path/to/connector/');
var collection = connector.get('mycollection');
collection.find({});
I don't think it would be difficult to implement this in a pull request, the only issue would be making the uri optional for monk.
I like this future from mongoose as you do not need to handle dependency injection.
What do you think?