在connection.close()之后,MongoDB连接并不总是关闭

时间:2016-07-18 15:11:56

标签: node.js mongodb

我有一个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连接仍保持打开状态。我现在看这个已经有一段时间了,但是不明白什么可能导致这种行为?

1 个答案:

答案 0 :(得分:0)

如果要关闭连接,是否尝试在成功连接后考虑使用.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