Mongodb nodejs native driver close the connection or not

Is it good in nodejs to open the mongodb connection for each request and close it in the callback?

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();
                }

      });
    });

Some said that opening / closing the mongodb connection for each request is not required, since after opening the connection pool can be shared.

The question is how to maintain and share this pool? Is the mongoose automatic?

In particular, while waiting or disconnecting mongodb, is it necessary to reconnect it?

I find conflicting answers here to close the mongodb connection for each request or not

Almost all of the nodejs mongodb native driver online docs and sample code that I read, db.open () is paired with db.close () somewhere in the callback.

, , christkv, :

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);
                }

      });
    });
+5
2

, , . , , , . , "" db . db - , db .

+5

, .

mongodb , 5 . maxPoolSize. auto_reconnect.

+8

All Articles