node.js 为什么MongoDB Node Driver生成实例池销毁错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39029893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:30:26  来源:igfitidea点击:

Why is the MongoDB Node Driver generating instance pool destroyed errors?

node.jsmongodb

提问by ra9r

When I run the following code I am getting the error message 'MongoError: server instance pool was destroyed'. Any idea why or how to fix this?

当我运行以下代码时,我收到错误消息“ MongoError:服务器实例池已销毁”。知道为什么或如何解决这个问题吗?

var csv = require('./importer.js');
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://.....';


MongoClient.connect(url, function(err, db) {

    assert.equal(null, err);
    console.log("Connected correctly to server.");

    csv.foreach('data/airports.csv', function(airport){
        db.collection('airports').insertOne(airport, function(err, result) {
            if(err) {
                console.log(err)
            } else {
                console.log("Inserted: " + airport.ident);
            }
        });
    });

    db.close();
});

回答by JohnnyHK

csv.foreachand the insertOnecalls are (presumably) both async, so you're calling db.close()before your inserts have completed.

csv.foreach并且insertOne调用(大概)都是异步的,因此您在db.close()插入完成之前调用。

You need to come up with a way of waiting to call db.close()until all your inserts' callbacks have been called. How to do that depends on how your csv module works, but using something like the async modulecan help with the async flow control.

您需要想出一种等待调用的方法,db.close()直到调用了所有插入的回调。如何做到这一点取决于您的 csv 模块的工作方式,但使用类似async 模块的东西可以帮助进行异步流控制。

回答by Kathy

I have same issue, after calling 'db.close()' together with async npm, this problem is resolved.

我有同样的问题,在调用 'db.close()' 和 async npm 后,这个问题就解决了。

回答by Stephanie

Try using a for...ofinstead of forEach. This solved my problem, although I am using async/await.

尝试使用for...of代替forEach。这解决了我的问题,尽管我使用的是 async/await。