First off, I'm fairly new in terms of knowing the performance cost of making a database connection from the server, so excuse me if I say something I may not have meant.
I'm currently taking a mongodb class for node.js, and I was really fascinated just how simple and elegant the code was for a blog server which they initially provided (We mainly just implement the queries to the database). It looks like this:
var express = require('express')
, app = express()
, cons = require('consolidate')
, MongoClient = require('mongodb').MongoClient
, routes = require('./routes');
MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) {
if(err) throw err;
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
routes(app, db);
app.listen(3000);
console.log('Express server listening on port 3000'); });
As you can see, it makes a database connection before the server is configured to do anything. Is it okay to use this pattern for production? It just seems so modular because the db is passed to the index.js where it handles all the routing.
What I have previously been doing is making a connection upon each request that queries the database and closing it (with the pg module). I'm actually not sure if this is a good idea either. But I would like some confirmation that such a pattern I describe above is okay; If not, maybe provide an alternative and explain why (alternative structure/pattern for mongodb and/or pg not an alternate module like mongoose).
Thanks!