MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

NodeJS - MongoDB:Verwenden Sie eine öffnende Verbindung

Wenn Sie require('somemodule') benötigen und dann ein zweites Mal erneut anfordern, wird die BEREITS geladene Instanz verwendet. Damit können Sie ganz einfach Singletons erstellen.

Also - innerhalb von 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;

Dann innerhalb von 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);
  })
}

Und innerhalb von b.js :

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

Die Idee ist, wenn beide a.js und b.js rufen Sie getMongoCollection auf , beim ersten Mal wird eine Verbindung hergestellt und beim zweiten Mal wird die bereits verbundene zurückgegeben. Auf diese Weise wird sichergestellt, dass Sie dieselbe Verbindung (Socket) verwenden.