EADDRINUSE Node.js MongoDB 回调问题

EADDRINUSE Node.js MongoDB Callbacks issue

问题:(node.js 应用程序 + mongodb 本机驱动程序) 我有一个 JSON 文件,其中包含超过 60000 个 Json Documents.the 文档,始终有创建日期和名为 vid 的唯一 ID。我需要插入一个 MongoDB 集合。 我需要插入新的视频或更新已存在的视频和另一个更新的文档。

我已经做了: https://github.com/TelmoIvo/PFC/blob/master/cfginit.js

发生了什么: 在 inserting/updating 类似 500 次并收集到 287 个文档后,我收到此错误: AssertionError: null == { [MongoError: connect EADDRINUSE] name : 'MongoError', message: 'connect EADDRINUSE' } 在行 assert.equal (null, err);

根据我的阅读,它说我与数据库的连接已经在使用中。但是每次我 insert/update 之后我都会关闭。

有什么建议吗?

我不会每次都打电话给 MongoClient.connect。这导致大量连接一直打开和关闭,这导致超载 mongo。你应该让 MongoClient 管理连接池。更改它,以便您存储来自 MongoClient.connect 的 db 对象,也许在您的 init 文件中添加类似

的内容
//store this outside your init so its accessible to other functions
//this is what you will use to access the database
var db;

//add this to your init function
MongoClient.connect(url, function(err, database){
    db = database;
}

然后在您要添加和更新的函数中使用您存储的 db 对象来更新您的集合,您将不需要一直打开连接。您可以删除所有 MongoClient.connect 代码并且不调用 db.close() 因为您的连接正在共享给对象,所以让 MongoClient 管理它们。