Skip to content

Provide Constructor for MongoDB Connection Reusing #132

@ihsanciftci

Description

@ihsanciftci

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:

https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions