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){
db.collection("some_collection").findOne(doc, function(err,item){
if(err){
res.send(err);
db.close();
}else{
res.send(item);
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(){
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{
res.send(item);
}
});
});
}else {
p_db.collection("some_collection").findOne(doc, function(err,item){
if(err){
res.send(err);
}else{
res.send(item);
}
});
});