anda dapat memiliki perpustakaan yang membungkus semua ini dengan baik - itu berarti hanya satu koneksi ke database yang akan dibuka dan koneksi (terbuka) yang sama akan dikembalikan untuk permintaan kedua - jika Anda mendapatkan 1000+ per detik, ini masalah make-or-break (yaitu tidak membuka kembali koneksi setiap permintaan)...
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;