//products.csv | uniqueCode | name | |:---------- | --------:| | 0001 | mouse | | 0002 | keyboard | | 0003 | monitor | | 0001 | mouse |
//code to convert csv to json and to save the data to mongodb
const csv = require("csvtojson");
router.post("/uploadProducts", async (req, res) => {
const products = await csv().fromFile("./products.csv");
try {
products.map(async (pdata) => {
let uniqueCode= await Product.findOne({
product_code: pdata.productCode,
});
if (!uniqueCode) {
//create new object
let product = new Product({
product_code: pdata.productCode,
product_name: pdata.name,
});
await product.save();
}
});
res.send("success");
} catch (err) {
console.error(err);
}
})
in the above code I check if the unique code already exists in the database. If not then create new object else ignore that object. so basically I'm trying to remove duplicates while saving the data.
But the problem here is that the duplicates are also getting saved in the db. In the products.csv file 1st row has unique code of 0001 and same unique code in the last row. So while mapping the objects the last object should have been ignored but it's not, it is getting saved anyways.
//once mapping is done then only the data is getting saved..All at once.
// creating local array and comparing the objects works. But I want a solution which can work directly with the mongodb .
can anyone help me with this?