user1255808
user1255808

Reputation:

NodeJS - MongoDB: use an opening connection

It is better to open a new connection or re-use ? when using module, because I'm used to separate my code into several files.

a.js

module.exports = function (req, res) {

  new mongodb.... (err, db) { // open a connection
    b(function (err, result) {
      db.close(); // close the connection
      res.send(result);
    });
  });

};

b.js

// re-open a connection ? or take the connection of "a.js" ? (passing "db")

When asynchronous, one must be careful to continue using the same connection (socket). This ensures that the next operation will not begin until after the write completes.

Thanks !

Upvotes: 3

Views: 2624

Answers (1)

Bino Carlos
Bino Carlos

Reputation: 1367

When you require('somemodule') and then require it again a second time, it will use the ALREADY loaded instance. This lets you create singletons quite easily.

So - inside of sharedmongo.js:

var mongo = require('mongodb');

// this variable will be used to hold the singleton connection
var mongoCollection = null;

var getMongoConnection = function(readyCallback) {

  if (mongoCollection) {
    readyCallback(null, mongoCollection);
    return;
  }

  // get the connection
  var server = new mongo.Server('127.0.0.1', 27017, {
    auto_reconnect: true
  });

  // get a handle on the database
  var db = new mongo.Db('squares', server);
  db.open(function(error, databaseConnection) {
    databaseConnection.createCollection('testCollection', function(error, collection) {

      if (!error) {
        mongoCollection = collection;
      }

      // now we have a connection
      if (readyCallback) readyCallback(error, mongoCollection);
    });
  });
};
module.exports = getMongoConnection;

Then inside of a.js:

var getMongoConnection = require('./sharedmongo.js');
var b = require('./b.js');
module.exports = function (req, res) {
  getMongoConnection(function(error, connection){
    // you can use the Mongo connection inside of a here
    // pass control to b - you don't need to pass the mongo
    b(req, res);
  })
}

And inside of b.js:

var getMongoConnection = require('./sharedmongo.js');
module.exports = function (req, res) {
  getMongoConnection(function(error, connection){
    // do something else here
  })
}

The idea is when both a.js and b.js call getMongoCollection, the first time it will connect, and the second time it will return the already connected one. This way it ensure you are using the same connection (socket).

Upvotes: 6

Related Questions