title: How to open and maintain connections to multiple Mongo databases correctly in Node.js?
body: <p>I'm completely new to Node.js and the Mongo db. However, I'd like to start a first project to get acquainted to all that stuff.</p>
  
  <p>The server app will be express based and I figured out to use three distinct mongo databases for appDdata, sessionData and userData. Now I have a really hard time to figure out how to connect to these databases and how to maintain the connections and pass around access objects.</p>
  
  <p>In most of the express/mongo tutorials, there are toy examples doing it like this:</p>
  
  <pre><code>MongoClient.connect('mongodb://localhost:27017/blog', function(err, db) {
  "use strict";
  if(err) throw err;
  
  // Register our templating engine
  app.engine('html', cons.swig);
  app.set('view engine', 'html');
  app.set('views', __dirname + '/views');
  
  // Express middleware to populate 'req.cookies' so we can access cookies
  app.use(express.cookieParser());
  
  // Express middleware to populate 'req.body' so we can access POST variables
  app.use(express.bodyParser());
  
  // Application routes
  routes(app, db);
  
  app.listen(8082);
  console.log('Express server listening on port 8082');
  });
  </code></pre>
  
  <p>That menas, I connect to the database and all my app lives in the callback of that connection call. Besides I really don't kike the idea of my whole app living in the callback, it get's worse when I have multiple database connections: The app will live in the callback of a callback of a callback...
  (And this will lead to a real indentation nightmare.)</p>
  
  <p>My first idea was to place the connection calls and then export the db objects I receive in the callback to some (module-)globals. </p>
  
  <p>But how to handle the situation, when the connection is not yet established or died? </p>
  
  <p>All in all, I'm still lacking a good idea of how to connect the databases and reuse these connections later in my app logic.</p>
  
  <p>I'm sure this is not a very unusual situation, so please, please help me out and point me to some advice how to handle this.</p>
  
  <p>Big Big Thanx!</p>
  
  <p>Felix</p>