是否在nodejs中为每个请求打开mongodb连接并在回调中关闭它是一个好习惯?mongodb nodejs本地驱动程序是否关闭连接
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();
}
});
});
有的说,对每个请求打开/关闭的mongodb连接不是必要的,因为一旦打开,连接池可以被共享。
问题是如何维护和共享该池?猫鼬是否已经自动做到了这一点?
尤其是,在mongodb超时或断开连接时,是否需要重新连接?
我在这里找到答案矛盾close mongodb connection per request or not
几乎所有的在线文档nodejs mongodb native driver和示例代码我看了,一个db.open()是搭配db.close()某处回调。
因为如果连接池是共享的,一个可能的代码 根据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);
}
});
});
几个月前我读了mongoose src,他们为每个集合打开一个连接,所以它只是缓存在变量中。不知道他们可能会改变。 我写了一个连接模块,并在app.listen之前运行它。 – wayne 2013-04-30 23:42:41