Question

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!

Was it helpful?

Solution

What you are doing is fine. node-postgres uses collection pooling, meaning you can open the connection once and reuse it. For many applications, pooling the database connections is preferred since it is more efficient than opening and closing them for every request. However, if you have long-lived database connections for some reason, then you may not want to pool database connections, since you run the risk of depleting the database pool. According to the source code, the default number of connections in the pool is 10, but you can turn off connection pooling by setting the number to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top