nodejs not terminate after db.close()

243 Views Asked by At

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.

0

There are 0 best solutions below