Uploading CSV files as MongoDB documents using node.js
I think the problem you have right now is that you don't have an identifier in the document which can help you differentiate which two files you're comparing.
Since your use case is to just compare two documents(json) in a collection using a filename (unique identifier).
Sr | Cheque_No | Amount |
---|---|---|
1 | 3141341243 | 1234 |
2 | 3141341244 | 4000 |
3 | 3141341245 | 2000 |
If your csv file looks like above
You should model data in this way
{ "filename": "xyz...", //save from the filename you're importing "csvData": [ { Sr: 1, Cheque_No: 3141341243, Amount: 1234, }, { Sr: 2, Cheque_No: 3141341244, Amount: 4000, }, { Sr: 3, Cheque_No: 3141341244, Amount: 2000, }, ... ]}
Then you can query mongodb collection using filename as a query parameter, and write a custom logic or use a 3rd party library to compare two json documents (csvData)
const mongoose = require("mongoose");const rowSchema = new mongoose.Schema({ Sr: { type: String, required: true, }, Cheque_No: { type: String, required: true, }, Amount: { type: String, required: true, },});const csvSchema = new mongoose.Schema({ fileName: { type: String, required: true }, csvData: { type: [rowSchema], required: true },});module.exports = mongoose.model("csvRecords", csvSchema);
app.post("/upload-csv", uploads.single("csv"), (req, res) => { //convert csvfile to jsonArray const fileName = req.body.fileName csv() .fromFile(req.file.path) .then((jsonObj) => { //finding the document using fileName and setting csvData as the jsonObj sheetModel.findOneAndUpdate({ fileName: fileName }, {$set: { csvData: jsonObj, fileName: fileName}, { upsert: true }}, (err, data) => { if (err) { res.status(400).json({ message: "Something went wrong!", }); } else { res.status(200).json({ message: "File Uploaded Successfully!", result: data, }); } }); });});
Please check for syntax, implementation would be something similar like this.