Node.js 如何关闭数据库和http连接
我正在尝试阅读MongoDB,并将内容打印到网页上。我正在使用mongodb模块读取Mongo 我能够成功地读取数据并将其打印到网页上,但我无法确定何时关闭数据库以及何时结束http连接。因此,我的网页会打印结果,但会一直等待服务器发送内容 我提到了以下问题,但无法理解在这个特定场景中我需要做什么:Node.js 如何关闭数据库和http连接,node.js,mongodb,Node.js,Mongodb,我正在尝试阅读MongoDB,并将内容打印到网页上。我正在使用mongodb模块读取Mongo 我能够成功地读取数据并将其打印到网页上,但我无法确定何时关闭数据库以及何时结束http连接。因此,我的网页会打印结果,但会一直等待服务器发送内容 我提到了以下问题,但无法理解在这个特定场景中我需要做什么: 这是我的密码: /* Opens the secondary collection and goes through each entry*/ var getClientIDs = fun
/* Opens the secondary collection and goes through each entry*/
var getClientIDs = function(collect, res) {
db.collection(collect, function(err, collection) {
var cursor = collection.find();
cursor.each(function(err, item) {
if(item != null) {
console.log(item['_id'] +"\t" + item['name']);
res.write(item['_id'].toString());
res.write("  ");
res.write(item['name'].toString());
res.write("</br>");
}
/*else {
res.end("The End");
db.close();
} Closes connection before other stuff is done. */
});
});
}
/* Opens the main collection and goes through each entry*/
var openCollection = function(collect, res) {
console.log(green);
// Establish connection to db
db.open(function(err, db) {
// Open a collection
db.collection(collect, function(err, collection) {
// Create a cursor
var cursor = collection.find();
// Execute the each command, triggers for each document
cursor.each(function(err, item) {
if(item != null) {
getClientIDs(item['_id'], res);
}
/* else {
db.close();
} This closes the connection before other stuff is done */
});
});
});
}
/* Start Here */
var http = require('http');
var port = 8888;
http.createServer(function (req, res) {
res.writeHead(200,{"Content-Type": "text/html; charset=utf-8"});
openCollection('company',res);
}).listen(port);
我没有这样创建集合。这就是我必须要处理的,我要创建一个脚本,它只需在网页上打印ID和名称
使用我的代码,网页将打印:
A001-01 foo
A001-02 bar
A002-01 foo2
A002-02 bar2
谢谢。当您使用本机驱动程序打开MongoDB连接时,您实际上打开了一个包含5个连接的池(默认情况下)。因此,最好在应用程序启动时打开该池并保持其打开状态,而不是在每次请求时打开并关闭该池
关闭HTTP响应的过程是正确的;只需调用
res.end()代码>当响应完成时(即光标中的项
为null
时。每个
回调)。我厌倦了在item==null但不在网页上打印任何内容的情况下添加res.end()。虽然my console.log()打印条目。因此,看起来res.end()发生在从数据库获取项目之前。而且,如果我不关闭数据库连接并刷新浏览器,它会说错误:数据库对象已连接,无法多次调用open
我在页面刷新时修复了数据库关闭错误。我在http.createServer()中添加了一个db.close()
。每次刷新页面时,都会调用此方法并关闭数据库连接,然后再将责任转移到openCollection()
。仍然需要考虑关闭http连接。添加了另一个黑客。我使用res.connection.setTimeout(10000)
使页面在10秒后超时,因此我的浏览器不会永远等待。这些黑客补丁并不是最好的选择:(@RBK我不是说你应该保持代码不变,只是不关闭数据库连接,我是说你应该在listen
调用之前打开数据库池,然后再启动应用程序。我仔细查看了你的其余代码,我不明白你为什么要在openConnection
中迭代集合再次为集合中的每个项目输入getClientId
。这就是为什么res.end()
调用不能按预期工作的原因。
A001-01 foo
A001-02 bar
A002-01 foo2
A002-02 bar2