sql >> Database teknologi >  >> NoSQL >> MongoDB

Node.js Mongodb-native driverforbindelsesdeling

du kunne have et bibliotek, der pakker alt dette pænt ind - det betyder, at kun én forbindelse til databasen vil blive åbnet, og den samme (åbne) forbindelse vil blive returneret for den anden anmodning - hvis du får 1000+ pr. sekund, er dette et make-or-break-problem (dvs. ikke at genåbne forbindelsen hver anmodning)...

users.js :

var connections = require('./connections.js');

var serverCache = connections('127.0.0.1', 27017); 

module.exports = {
  create: function(newData, callback){
    serverCache('main', 'users', function(e, collection){
      collection.insert(newData, callback);
    })
  }
}

connections.js

var mongo = require('mongodb');

// a mongo connection cache
// pass in host & port
// it returns a function accepting dbName, collectionName & callback
var mongoCache = function(host, port){

  // keep our open connections
  var mongoDatabases = {};

  var ensureDatabase = function(dbName, readyCallback){
    // check if we already have this db connection open
    if(mongoDatabases[dbName]){
      readyCallback(null, mongoDatabases[dbName]);
      return;
    }

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

    // get a handle on the database
    var db = new mongo.Db(dbName, server);
    db.open(function(error, databaseConnection){
      if(error) throw error;

      // add the database to the cache
      mongoDatabases[dbName] = databaseConnection;

      // remove the database from the cache if it closes
      databaseConnection.on('close', function(){
        delete(mongoDatabases[dbName]);
      })

      // return the database connection
      readyCallback(error, databaseConnection);
    })
  }

  var ensureCollection = function(dbName, collectionName, readyCallback){

    ensureDatabase(dbName, function(error, databaseConnection){
      if(error) throw error;

      databaseConnection.createCollection(collectionName, function(error, collection) {
        if(error) throw error;

        // return the collection finally
        readyCallback(error, collection);
      })

    })
  }

  return ensureCollection;
}

module.exports = mongoCache;


  1. MongoDB GPG - Ugyldige signaturer

  2. Saml MongoDB-resultater efter ObjectId-dato

  3. Vil du inkludere et felt (_id eller andet) i mongodb-projektsammenlægning?

  4. MongoDB $uge