Right now, the "persists()" return imidiately, even though the insert hasn't finished. This is due to the asyncronus nature of javascript/nodejs.
You need to serialize the insert operations so you don't clog the server. Use async.eachSeries()
Your "persists" function should use a callback to notify the caller that it has finished. Somehing like this:
persists(req, res, result, collectionName, headers, callback){
MongoClient.connect(MONGODB_URI, function (err, database) {
var collection = database.collection(collectionName);
async.eachSeries(jsonResult,
function(obj, cb){
for (var prop in obj) {
if (headers[prop] == 'Date') {
obj[prop] = new Date(obj[prop].replace(/(\d{2})-(\d{2})-(\d{4})/,"$2/$1/$3"));
} else if (headers[prop] == 'Integer') {
obj[prop] = parseInt(obj[prop]);
} else if (headers[prop] == 'Float') {
obj[prop] = parseFloat(obj[prop]);
}
}
collection.insert(obj, function (err, result) {
cb(err);
});
},
function(err){
callback();
}
);
});
}
And then to use it
persists(req, res, result, collectionName, headers, function(){
console.log("insert finished");
});