Is it a good practice in nodejs to open mongodb connection per 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 mongodb connection on each request isn't necessary, since once opened, a pool of connections can be shared.
The question is how to maintain and share that pool? Is mongoose doing that automatically already?
Especially, on mongodb timeout or disconnect, does it need to be reconnected?
I find contradictory answers here close mongodb connection per request or not
Almost all the online doc nodejs mongodb native driver and example code I read, a db.open() is paired with db.close() somewhere in the callback.
Because if a pool of connection is shared, one might code
According to christkv's answer, one might 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);
}
});
});