Reputation: 143
I'm writing some simple web app with Node.JS and want to use mongoDB as main data storage.
Node-mongodb-native driver requires to make chained calls before you actually can query or store data (open DB connection, authenticate, get collection).
Where is the best place to do this initialization - within each request handler or globally, when initializing application?
Upvotes: 3
Views: 1464
Reputation: 1367
You are MUCH better putting the Mongo initialization outside of your request handler - otherwise it will re-connect for every page that is served:
var mongo = require('mongodb');
// our express (or any HTTP server)
var app = express.createServer();
// this variable will be used to hold the collection for use below
var mongoCollection = null;
// 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 Db('testdb', server);
db.open(function(error, databaseConnection){
databaseConnection.createCollection('testCollection', function(error, collection) {
if(!error){
mongoCollection = collection;
}
// now we have a connection - tell the express to start
app.listen(80);
});
});
app.use('/', function(req, res, next){
// here we can use the mongoCollection - it is already connected
// and will not-reconnect for each request (bad!)
})
Upvotes: 2