sale108
sale108

Reputation: 597

Exporting from Mongoose to CSV with Mixed Objects

I went over tens of libraries and functions. I probably lack some knowledge in the field, cuz I can't figure out what adjustments need to be done in order to modify the existed libraries, or at least define the properties properly to make it work.

I have the following structure in my DB:

var keywordSchema = new mongoose.Schema({
   keyword: { type: String, lowercase: true },
   addedToDB: {type: Date, default: Date.now},
   updates: [{ 
      date: {type: Date, default: new Date},
      traffic: Number,
      difficulty: Number,
      competition: Number,
      updated: {type: Date, default: Date.now}
   }]
});

Now, I want to have the ability to export all words to a CSV file with the following headers:

Keyword, Traffic, Difficulty, Competition, Date

Where each row is a different keyword AND the traffic, difficulty, competition, and date, are the most recent data for this word in the DB( the most recent data is the index in the "updates" array that his "date" value is the most recent one).

I can handle the finding the most recent one, I just couldn't find a good way to export it.

Help please?

If something is unclear, please let me know

Upvotes: 1

Views: 1003

Answers (1)

Lalit Goswami
Lalit Goswami

Reputation: 816

Have you tried json2csv module ?

e.g :

var json2csv = require('json2csv');
var fields = ['keyword', 'traffic', 'difficulty','competition','date'];
var fieldNames = ['Keyword', 'Traffic', 'Difficulty', 'Competition', 'Date'];

var myData = // YOUR DATA
try {
  var result = json2csv({ data: myData, fields: fields,fieldNames:fieldNames });
  fs.writeFile('word-ranker.csv', result, function(err) {
    if (err) throw err;
        console.log('file saved');
    });
} catch (err) {
  console.error(err);
}

NOTE : Make sure myData should have direct fields.

Hope this help You.

Upvotes: 1

Related Questions