title: mongodb nodejs native driver close connection or not
body: <p>Is it a good practice in nodejs to open mongodb connection per each request, and close it in the callback?</p>
  
  <pre><code>app.get('/some_route', function(){
        MongoClient.connect(url,function(err, db){
            //some db query with callback
            db.collection("some_collection").findOne(doc, function(err,item){
                 if(err){
                        res.send(err);
                        //close db connection 
                        db.close();
                  }else{
                        //do something with item
                        res.send(item);
                        //close db connection 
                        db.close();
                  }
  
        });
      });
  </code></pre>
  
  <p>Some said that opening/closing mongodb connection on each request isn't necessary, since once opened, a pool of connections can be shared. </p>
  
  <p>The question is how to maintain and share that pool? Is mongoose doing that automatically already? </p>
  
  <p>Especially, on mongodb timeout or disconnect, does it need to be reconnected?</p>
  
  <p>I find contradictory answers here <a href="https://stackoverflow.com/questions/10656574/how-to-manage-mongodb-connections-in-a-nodejs-webapp">close mongodb connection per request or not</a></p>
  
  <p>Almost all the online doc <a href="http://mongodb.github.io/node-mongodb-native/api-generated/db.html" rel="nofollow noreferrer">nodejs mongodb native driver</a> and example code I read, a db.open() is paired with db.close() somewhere in the callback.</p>
  
  <p><del>Because if a pool of connection is shared, one might code</del>
  According to christkv's answer, one might code:</p>
  
  <pre><code>var p_db=null;
  var c_opt = {server:{auto_reconnect:true}};
  
  app.get('/some_route', function(){
        //pseudo code
      if (!p_db){
             MongoClient.connect(url, c_opt, function(err,db){
                    p_db = db;
                    p_db.collection("some_collection").findOne(doc, function(err,item){
                    if(err){
                        res.send(err);                          
                    }else{
                        //do something with item
                        res.send(item);
                    }
  
               });
             });
         }else {
            p_db.collection("some_collection").findOne(doc, function(err,item){
                 if(err){
                        res.send(err);
                  }else{
                        //do something with item
                        res.send(item);
                  }
  
        });
      });
  </code></pre>