Automattic / monk

The wise MongoDB API
MIT License
1.85k stars 182 forks source link

cache database connection in module space #70

Open bodokaiser opened 10 years ago

bodokaiser commented 10 years ago

I like this future from mongoose as you do not need to handle dependency injection.

var monk = require('monk');

// connection still the same
monk('localhost/test');

// however this will return collection
monk.get('users');

What do you think?

faridnsh commented 10 years ago

How do we handle multiple connections?

bodokaiser commented 10 years ago

over some mongodb connection pool or you just take the returned db instance and handle it your self

scurker commented 7 years ago

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.