Anirudh
Anirudh

Reputation: 41

How to save array of objects in MongoDB.in a Node.js application

I am trying to upload an Excel file to MongoDB database.

I used below NPM package manager to convert Excel data to MongoDB

mongoXlsx.xlsx2MongoData(path, model, function(err, data){
  console.log(data); // (This variable data has an array of objects, each object is a row in Excel.)
}); 

The image attached has the data. Now, I want to upload this 'data' (That has an array of objects) into MongoDB. How can I do that? Please suggest.enter image description here

Upvotes: 1

Views: 1065

Answers (1)

Hayfa
Hayfa

Reputation: 147

You can use a for loop to iterate through the array , and insert each element of the array in a single mongoDB document :

for ( var counter=0 ;counter<data.length;counter++)
{
    dataBaseName.colletionName.insertOne(data[counter]);
}

but before that, as @zenwraight pointed out, you should convert your data into correct json format , for example Name : 'ABC' should become 'Name' : 'ABC' (same goes for other fields)

Upvotes: 1

Related Questions