Everything is cool and all, and it’s great, however, I have a Export to CSV button available for users too, I want them to be able to export this query to CSV. How do I go about that?
const csvString = Papa.unparse(myQueryObject); // unparse generates CSV from your Object
const a = document.createElement('a'); // create a simple link to a resource where your payload is your encoded CSV
a.href = `data:text/csv;charset=utf-8,${encodeURIComponent(csvString)}`;
a.download = 'query.csv'; // or whatever you wanna call it
a.click();
Fair warning, last I checked, this doesn’t work for very LARGE files on Google Chrome for some reason…but you shouldn’t have a problem for your use case.
I understand that I need the myQueryObject, so I tried this
const csvString = Papa.unparse(Trips.find({"year": {$eq: yearNum}, "userId" : {$eq: Meteor.userId()} } , {sort:{createdAt: -1}})); // unparse generates CSV from your Object
const a = document.createElement('a'); // create a simple link to a resource where your payload is your encoded CSV
a.href = `data:text/csv;charset=utf-8,${encodeURIComponent(csvString)}`;
a.download = 'query.csv'; // or whatever you wanna call it
a.click();
For some reason the CSV is empty, also how do I store that query output as an object, so I can use it later on?
You said you wanted to store the query object not the results. Also, make sure to read the docs carefully, because Collection.find() returns a Mongo cursor that points to your data, not your actual results.
To get what you actually want, you need to do Trips.find(yourQuery).fetch(), which fetches the results of the query from the returned cursor.
Yeah +1 it’s a better idea to use a library like pfafman:filesaver or https://github.com/eligrey/FileSaver.js/ because just hacking together an <a> tag with a big payload has inconsistent results across different browsers.
Trips.find() returns a cursor - that’s like a description of how to get the results without actually getting them. Trips.find().fetch() actually gets the results from the cursor. So your arrayParts is a cursor and arrayParts.fetch() will get the results using the cursor.
find returns a cursor. It does not immediately access the database or return documents. Cursors provide fetch to return all matching documents, map and forEach to iterate over all matching documents, and observe and observeChanges to register callbacks when the set of matching documents changes.