1

My node script not terminates even though I tried to close all my connections. Of course I can terminate it with process.exit, but I want to know what the reason behind this. The wtfnode plugin showed I have a lot of open mongo connections. It seems like every db insert has their own.

The code:

var fn = function getFromDb(dbName) {
    return new Promise(function(resolve, reject) {
        var sourceDB = mongo.db(dbName);
        sourceDB.collection(coll).find().toArray(function(err, result) {
            sourceDB.close();
            if (err) {
                reject(err);
            } else {
                resolve([result, dbName]);
            }
        });
    });
}
var actions = inputDbArr.map(fn);

var results = Promise.all(actions);

results.then(data => { 
    for (var i in data) {
        for (var k in data[i][0]) {
            data[i][0][k].city = data[i][1];
            destinationDB = mongo.db(destDBName);
            destinationDB.collection(destColl).insert(data[i][0][k], function(err, result) {
                if (err) {
                    throw err;
                } else {
                    if (i == data.length - 1 && k == data[i][0].length - 1) {
                        destinationDB.close();
                        process.exit(); //For some reason there are still open connections left
                    }
                }
            });
        }
    }
});

Thank you in advance.

Paxi
  • 111
  • 11
  • Have you looked at the documentation? http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#close – CherryNerd Jan 16 '17 at 15:48
  • 2
    Your `for` loops are synchronous so `i` and `k` will be at their final values before the first `insert` callback is called. So your `destinationDB.close()` call occurs before all the `insert` operations have completed. – JohnnyHK Jan 16 '17 at 16:05
  • @JohnnyHK you are right. And with the insert I opened a connection again and again. – Paxi Jan 17 '17 at 10:25

0 Answers0