1

I need your advice.

I want to handle server with multiple MongoDB databases and managing them throw rest API (node.js).

How can I manage my databases? Connect to all databases when server up is not a good idea. Connect to the database for creating a document in DB and disconnect after this also don’t sound like a good idea... So how can I do it? Store an array with connections and disconnect after few minutes of unuse? What do you think?

nyi
  • 3,123
  • 4
  • 22
  • 45

1 Answers1

0

Yeah, I would probably do something similar to what you're describing. I couldn't tell you if this code is fully functional, but here's a five-minute go at it:

class TimedConnection {
  constructor(uri) {
    this.uri = uri;
    this._connected = false;
    this.disconnect = this.disconnect.bind(this);
  }

  connect() {
    return new Promise((resolve, reject) => {
      if (!this._connected) {
        const db = this.db = mongoose.createConnection(this.uri);

        db.once('open', resolve());
        // whatever
      }

      clearTimeout(this._connectionTimeout);
      this._connectionTimeout = setTimeout(this.disconnect, 300000)

      return resolve(this.db);
    })
  }

  query() {
    this.connect().then((db) => {
      // something with `db`
    })
  }

  disconnect() {
    this.db.disconnect();
    this._connected = false;
  }
}

const connectionMap = {
  objectsDatabase: new TimedConnection('mongodb://whatever'),
  personsDatabase: new TimedConnection('mongodb://whateverthing'),
  ...
};
Dan Crews
  • 3,067
  • 17
  • 20
  • Thank you! Very nice solution. I will try it. But I have a small question: what purpose of “this.disconnect = this.disconnect.bind(this);” in constructor? –  May 11 '18 at 16:20
  • Because we're passing `this.disconnect` to the `setTimeout` function, the `this` keyword will lose its context, and the function won't work anymore. By doing a `.bind` in advance, that function gets pre-hardwired with the `this` parameter, so this doesn't happen. – Dan Crews May 14 '18 at 19:12