我有一个 nodejs 应用程序正在执行一些 mongodb 数据库迁移。
一切始于
MongoClient.connect(`mongodb://${databaseHostname}:${databasePort}/${options.databaseName}`,
(connectionError, dbConnection) => {
if (connectionError) {
return cb(connectionError);
}
console.log('Opened connection to', databaseHostname, options.databaseName);
return cb(null, dbConnection);
});
以
结尾console.log('Close');
dbConnection.close((err) => {
if (err) console.log(err);
console.log('Closed');
});
中间发生了很多事情,创建了新的集合,重新排列了文档等等。但是从来没有打开过新的连接。该应用程序的输出是:
Opened connection to localhost testDatabase
[这里有很多其他日志]
Close
Closed
数据库日志是
2016-07-18T16:54:29.400+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:54336 #848 (1 connection now open)
2016-07-18T16:54:29.423+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:54337 #849 (2 connections now open)
2016-07-18T16:54:29.426+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:54338 #850 (3 connections now open)
[这里有很多插入和更新]
2016-07-18T16:58:06.493+0200 I NETWORK [conn849] end connection 127.0.0.1:54337 (2 connections now open)
2016-07-18T16:58:06.494+0200 I NETWORK [conn850] end connection 127.0.0.1:54338 (1 connection now open)
如您所见,即使调用了 dbConnection.close() 以阻止 nodejs 应用程序退出,一个 mongodb 连接仍保持打开状态。我已经关注这个问题很长时间了,但不明白是什么导致了这种行为?
最佳答案
如果你想关闭连接,你是否考虑过在连接成功后使用.finally()或.then()语句?
有点像
MongoClient.connect(`mongodb://${databaseHostname}:${databasePort}/${options.databaseName}`,
(connectionError, dbConnection) => {
if (connectionError) {
return cb(connectionError);
}
console.log('Opened connection to', databaseHostname, options.databaseName);
return cb(null, dbConnection);
}).then( () => {
dbConnection.close((err) => {
if (err) console.log(err);
console.log('Closed');
});
});
无论如何,我最近对 mongodb 连接做了一些研究,有些人说不建议关闭你的数据库。 Why is it recommended not to close a MongoDB connection anywhere in Node.js code?
此链接可能会进一步帮助您解决问题。
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
关于node.js - MongoDB 连接在 connection.close() 之后并不总是关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38440264/