title: Node.js and MongoDB, reusing the DB object
body: <p>I'm new to both Node.js and MongoDB, but I've managed to put some parts together from SO and the documentation for mongo.</p>
  
  <p>Mongo documentetion gives the example: </p>
  
  <pre><code>// Retrieve
  var MongoClient = require('mongodb').MongoClient;
  
  // Connect to the db
  MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
    if(!err) {
      console.log("We are connected");
    }
  });
  </code></pre>
  
  <p>Which looks fine if I only need to use the DB in one function at one place. Searching and reading on SO has shown me that I should not open a new connection each time, but rather use a pool and reuse the database object I get the first time. This answer is abundant on SO, but I'm not sure how to even get the DB object in the first place, and then how to reuse it.</p>
  
  <p>Say I have the Node.js code above in my App.js, and I then have differnt routes that need to run different operations on the db like:</p>
  
  <pre><code>app.post('/employee', function(req, res){
      //Put req.name in database
  });
  
  
  app.post('/car', function(req, res){
      //Put req.car in database
  });
  </code></pre>
  
  <p>How would I go about to put these two snippets together into something useful?</p>
  
  <p>I found a similar question in <a href="https://stackoverflow.com/questions/10108170/node-js-reuse-mongodb-reference">Node.js reuse MongoDB reference</a> , but from the looks of this ( <a href="http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html" rel="nofollow noreferrer">http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html</a> ) it looks like I should use MongoClient rather than db(). And I'm not sure it solves my problem either...</p>