Export a MongoDB collection to CSV or XLSX using Meteor / JavaScript

I want to export my collection to a CSV or XLSX file using the button (without logging in).

Is there an easy way to do this using Meteor / JavaScript?

+6
source share
3 answers

You can use something like https://github.com/eligrey/FileSaver.js to create Blob on the browser side and then offer it as a download.

client side js

var yourCSVData = "Col1Row1,Col2Row1\nCol1Row2,Col2Row2"; var blob = new Blob([yourCSVData], {type: "text/csv;charset=utf-8"}); saveAs(blob, "yourfile.csv"); 

Create your CSV in yourCSVData , then you can easily upload the file.

To create your CSV, you will have to use some kind of custom javascript. The thing with mongodb is that each document can have a different structure, which is very bad for documents like row / column.

You can use something like the violin given by Yvegeniy ( http://jsfiddle.net/sturtevant/vUnF9/ ) in the comments above, and this may help

 var data = MyCollection.find().fetch(); var yourCSVData = JSON2CSV(data); 
+10
source

Given the latest versions of Meteor 1.5 and the latest available Meteor packages to date, the following are the steps you need to follow to convert Mongo DB to a CSV collection (also readable from MS Office, like a charm.)

  • You should have below packages installed before any steps below,

     pfafman:filesaver harrison:papa-parse 
  • Consider a simple Blaze template (i.e. MyTemplate.html ) with the download link below,

     <template name="MyTemplate"> <body> <a href="#" role="button" class="download">Download</a> </body> </template> 
  • Similarly, you can have an event handler (that is, in MyTemplate.js ) to handle click download ,

     Template.MyTemplate.events({ 'click .download': function (event, template) { var data = MyCollection.find({}).fetch(); var csv = Papa.unparse(data); var blob = new Blob([csv], {type: "text/csv;charset=utf-8"}); saveAs(blob, "MyCollection.csv"); } }); 

NOTE When you click on the download link, you will not receive a pop-up window or dialog box to continue downloading, but it will automatically load silently for you.

+1
source

Template creates an excellent export system

  {{#each documents}} "{{field1}}","{{field2}}"<br/> {{/each}} 

The xlsx format, although ugly, lends itself to the same treatment.

Rendering an HTML page is the same. How to create pdf. Or generate SQL.

0
source

Source: https://habr.com/ru/post/952841/


All Articles