I have excel file which contains some records. Requirement is I have to convert it into Mongodb database. I looking NodeJS solution. Is there any way to do it??
Asked
Active
Viewed 2,384 times
-2
-
https://stackoverflow.com/questions/25241500/how-to-import-excel-file-xlsx-to-mongodb – arunp9294 Oct 19 '19 at 21:41
-
https://www.npmjs.com/package/mongo-xlsx – arunp9294 Oct 19 '19 at 21:41
1 Answers
0
'use strict';
const papa = require('papaparse');
const fs = require('fs');
//
// Read a text file form the file system.
//
function read (fileName) {
return new Promise((resolve, reject) => {
fs.readFile(fileName, 'utf8',
function (err, textFileData) {
if (err) {
reject(err);
return;
}
resolve(textFileData);
}
);
});
};
//
// Helper function to import a CSV file.
//
function importCsvFile (filePath) {
return read(filePath)
.then(textFileData => {
const result = papa.parse(textFileData, {
header: true,
dynamicTyping: true,
});
return result.data;
});
};
function exportToMongoDB (db, collectionName, data) {
return db[collectionName].insert(data);
};
const mongo = require('promised-mongo');
const db = mongo('localhost:27017/earthquakes', ['largest_earthquakes']);
importCsvFile('/code/data/earthquakes.csv')
.then(data => exportToMongoDB(db, 'largest_earthquakes', data))
.then(() => db.close())
.catch(err => {
console.error("An error occurred.");
console.error(err.stack);
});

Carlos Gutierrez
- 16
- 2
-
follow this source: https://github.com/Data-Wrangling-with-JavaScript – Carlos Gutierrez Oct 20 '19 at 00:39