I am parsing a CSV and process each record to insert it into my MongoDB using Mongoose. I already get an array out of the CSV correctly but when I start iterating over it using forEach (and async/await) it just stops there.
Here is my code:
const csv = require('csv-parser');
const fs = require('fs');
const Customer = require('../../app/models/Customers');
const projects = [];
const processRecords = async () => {
try {
const usableProjects = projects.filter((project) => project['cust_number customer']);
const customerNames = [...new Set(usableProjects.map((item) => item['Parent Name']))];
await customerNames.forEach(async (customerName) => {
console.log('Point 1');
const existingCustomer = await Customer.find({Name: customerName});
console.log('Point 2'); //<======= THIS CODE IS NEVER REACHED
if (existingCustomer.length > 0) {
console.log(`${customerName} already exists. Skipping...`);
return;
}
const customerRecord = usableProjects.find((project) => project['Parent Name'] === customerName);
const newCustomer = {
Name: customerName,
Source: 'CSV',
Initials: customerRecord.Initials,
Code: customerRecord.Codename,
};
const newCustomerRecord = await Customer.create(newCustomer);
if (newCustomerRecord) {
console.log(`Customer ${newCustomerRecord._id} created`);
}
});
} catch (err) {
console.log(err);
}
};
fs.createReadStream('customer_table.csv')
.pipe(csv())
.on('data', async (data) => projects.push(data))
.on('end', async () => {
processRecords();
});
And this is the output:
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
Point 1
I know this might have something to do with synchronous/asynchronous code not being handled corrected by me. But I've not been able to fix it. Thanks in advance.