Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

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();
});
like image 596
ra9r Avatar asked Aug 19 '16 01:08

ra9r


2 Answers

csv.foreach and the insertOne calls are (presumably) both async, so you're calling db.close() before your inserts have completed.

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 module can help with the async flow control.

like image 153
JohnnyHK Avatar answered Oct 14 '22 20:10

JohnnyHK


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

like image 2
Kathy Avatar answered Oct 14 '22 20:10

Kathy