我是Node.js和MongoDB的新手。这是我编写的用于检索数据的代码。
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://username:password@dbname.mongodb.net/test?retryWrites=true";
const client = new MongoClient(uri, {
useNewUrlParser: true
});
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
client.connect(err => {
client.db("fsdb").collection("subs").find({
sub: /sometext/i
}).toArray(function (err, result) {
if (err) throw err;
res.end(JSON.stringify(result));
// client.close(); -----> MongoError: Topology was destroyed
});
});
}).listen(80);
此代码可以正常工作。但这会在每个请求上打开一个新连接,并使它们保持打开状态。
如果我使用client.close();
会给我错误,
MongoError: Topology was destroyed
检索数据后如何关闭连接?
编辑:
因此,对于初学者来说,重复帖子中的答案有些沉重,我找到了自己的方法。将其发布为answer here。