I want to export my collection to a CSV or XLSX file by a button (no log-in system).
Is there a simple way to do that with Meteor/JavaScript?
Export MongoDB to CSV (e.g. Excel) Open the Export Wizard and select your export source. This screen only appears if you haven't chosen an item in the Connection Tree, run a previous query, or selected specific documents. Next, choose CSV as the export format then click Next.
So, to export data from the MongoDB database, MongoDB provides a command-line tool known as mongoexport. Using this tool you can exports data of a collection in JSON or CSV(comma-separated value) format. Moreover, we can also use features like limit and sort on a collection while exporting the data.
You could use something like https://github.com/eligrey/FileSaver.js to create a 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");
Build your CSV into yourCSVData
then you should be able to have the file downloaded very easily.
To build your CSV you would have to use some custom javascript. The thing with mongodb is that each document can have a different structure, which is very bad for row/column type documents.
You could use something like the fiddle given by Yvegeniy (http://jsfiddle.net/sturtevant/vUnF9/) in the comments above & it might help
var data = MyCollection.find().fetch();
var yourCSVData = JSON2CSV(data);
Considering latest Meteor 1.5 and latest available Meteor packages as of today, below are the steps you need to follow in order to convert Mongo DB Collection to CSV (also readable by MS Office like a charm.)
You need to have below packages installed prior to any steps below,
pfafman:filesaver
harrison:papa-parse
Consider a simple Blaze Template (i.e. MyTemplate.html) with a download link below,
<template name="MyTemplate">
<body>
<a href="#" role="button" class="download">Download</a>
</body>
</template>
Similarly you can have events handler (i.e. in MyTemplate.js) to handle "Download" link click event,
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 the download link, you will not get any popup or dialog box for you to proceed downloading, rather it will automatically download it silently for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With