-
Notifications
You must be signed in to change notification settings - Fork 63
Description
sharedb-mongo provides two ways of accessing a mongodb database:
a) takes a url, creates a client, connects to the server, accesses the database
b) takes a client, connects to the server, accesses the database
The second approach provides better flexibility and saves resource.
In fact, there is a better way:
c) takes a database
The third approach enables creating thousands of sharedb instances without hitting connection limitations since each connect() call creates another connection pool.
I'm not good at NodeJS but I changed the source code and it enabled running 4000 sharedb instances with 150 mongodb connections. I think this is a good result.
if (isLegacyMongoClient(client)) {
self.mongo = self._mongoClient = client;
}
else if(client.s) {
self.mongo = client;
self._mongoClient = client.s.client;
self._dbInstance = true;
}
else {
self.mongo = client.db();
self._mongoClient = client;
}
ShareDbMongo.prototype.close = function(callback) {
if (!callback) {
callback = function(err) {
if (err) throw err;
};
}
var self = this;
this.getDbs(function(err) {
// Ignore "already closed"
if (err && err.code === 5101) return callback();
if (err) return callback(err);
self.closed = true;
if(!self._dbInstance) {
self._mongoClient.close(function(err) {
if (err) return callback(err);
if (!self._mongoPollClient) return callback();
self._mongoPollClient.close(callback);
});
}
});
};
const db = require('sharedb-mongo')({
mongo: function (callback) {
mongoPromise.then(client => {
let mongoDb = client.db(appId);
try {
callback(null, mongoDb);
}
catch (error) {
console.log(error);
}
});
}
});
Notes:
Mongodb documents about connection pooling:
"To reduce the number of connection pools created by your application, we recommend calling MongoClient.connect once and reusing the database variable returned by the callback:"
See #56 (comment) for another discussion about this feature request.