Exporting table data in Meteor Blaze

I am encountering difficulties while trying to export a table to CSV in the Meteor/Blaze framework. I am following the guide on: [.

My Template.event is responsible for triggering the export button.

Template.export.onCreated( () => {
  Template.instance().subscribe('table');
});
Template.export.helpers({
  exportContacts() {
    return Contacts.find();
  }
});
Template.export.events({
  'click .export-data' () {
    MyAppExporter.exportAllContacts();
  }
});

The exportAllContacts() function is called from a global helper.

 MyAppExporter = {
    exportAllContacts: function() {
        var self = this;
        Meteor.call("exportContacts", function(error, data) {
            if ( error ) {
                alert(error);
                return false;
            }
            var csv = Papa.unparse(data);
            self._downloadCSV(csv);
        });
    },
    _downloadCSV: function(csv) {
        var blob = new Blob([csv]);
        var a = window.document.createElement("a");
        a.href = window.URL.createObjectURL(blob, {type: "text/plain"});
        a.download = "contacts.csv";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
}

The helper function calls a Meteor.method named exportContacts.

  Meteor.methods({
    exportContacts: function() {
        let fields = [
            "Email",
            “Some Contact",
            "Created Date",
            "Hard Bounce",
            "Unsubscribed"
        ];
        let data = [];
        let contacts = Contacts.find().fetch();
    for(let i = 0; i < contacts.length; i++) {
      let contact = contacts[i];
      let contactString = JSON.stringify(contact);
        _.each(contactString, function(c) {
        console.log("Inside Loop", contactString);
            data.push([
                c.contact.emailAddress,
                c.contact.someContact,
                c.contact.creationDate,
                c.contact.hardBounceBack,
                c.contact.unsubscribed
            ]);
        console.log("DATA", data)
        return {fields: fields, data: data};
        });
    }
  }
});

However, an error keeps occurring stating that “emailAddress is not defined exportContacts.js:20:17

20160426-22:00:47.957(-4)? Inside Loop {"_id":"dRnXRdZrbR9CYdmBx","contact":[{"emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcdd9cecfebdccecad8c7d285c8c4c6">[email protected]</a>","someContact":"No","creationDate":"N/A","hardBounceBack":"N/A","unsubscribed":"N/A"}]}

I20160426-22:00:48.029(-4)? Exception while invoking method 'exportContacts' ReferenceError: emailAddress is not defined
I20160426-22:00:48.029(-4)?     at server/methods/exportContacts.js:20:17
I20160426-22:00:48.029(-4)?     at Function._.each._.forEach (packages/underscore.js:142:22)
I20160426-22:00:48.029(-4)?     at _loop (server/methods/exportContacts.js:17:7)

I have been struggling to access the contacts despite logging them out (as seen in the logs above). Any assistance would be greatly appreciated.

ADDED LOGS let contacts = Contacts.find().fetch(); console.log(contacts)

I20160427-09:06:23.484(-4)? CONTACTS [ { _id: 'dRnXRdZrbR9CYdmBx', contact: [ [Object] ] },
I20160427-09:06:23.484(-4)?   { _id: 'LHmW4R9PLM5D7cZxr', contact: [ [Object] ] },
I20160427-09:06:23.484(-4)?   { _id: 'jBdqQXz2b8itXJowX', contact: [ [Object] ] },
I20160427-09:06:23.484(-4)?   { _id: 'bnDvNGX3i879z4wr2', contact: [ [Object] ] } ]

c.contact[0].emailAddress logged out

I20160427-09:22:08.142(-4)? Inside Loop {"_id":"dRnXRdZrbR9CYdmBx","contact":[{"emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ff9edfafbdfe8fafeecf3e6b1fcf0f2">[email protected]</a>","someContact":"No","creationDate":"N/A","hardBounceBack":"N/A","unsubscribed":"N/A"}]}
I20160427-09:22:08.217(-4)? Exception while invoking method 'exportContacts' TypeError: Cannot read property '0' of undefined
I20160427-09:22:08.217(-4)?     at server/methods/exportContacts.js:21:7
I20160427-09:22:08.217(-4)?     at Function._.each._.forEach (packages/underscore.js:142:22)
I20160427-09:22:08.217(-4)?     at _loop (server/methods/exportContacts.js:18:7)
I20160427-09:22:08.218(-4)?     at [object Object].exportContacts (server/methods/exportContacts.js:15:46)

Answer â„–1

When working with the _.each loop, make sure you are accessing the correct data items. Consider using a _.each loop instead of an outer for loop. For example:

let contacts = Contacts.find().fetch();
_.each(contacts, function(contact) {
  _each(contact.contact, function(c) {
      data.push(
          {
              "email": c.emailAddress,
              "contact": c.someContact,
              "creationDate": c.creationDate,
              "bounceBack": c.hardBounceBack,
              "unsubscribed": c.unsubscribed
          }            
  })
})

Try implementing this solution to resolve your issue. By looping through the outer contacts returned from the fetch and then iterating through the contact array within each element, you should be able to access the desired data efficiently.

Answer â„–2

The issue lies within this particular line:

_.each(contactString, function(c) {

The correct syntax should be: _.each(contact, function(c) {

Problem solved!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for refreshing a page upon submission

My Bootstrap Modal contains a form with Submit and Cancel buttons. The cancel button is working correctly and closes the Modal successfully. However, when I click on the Submit Button, the form submits successfully to the Web Service but the Modal does not ...

Using the spread operator to pass properties in React

Update: After delving deep into the documentation, @wawka has discovered that there may be some issues with the react-router-dom v^5.0.1 causing problems with the myLink2 component. It seems like a rewrite of this component may be necessary. In my React p ...

Upon a successful onChange event, the selected value reverts back to its default state

In my current project, I am creating a form where users can dynamically add or remove dropdowns to manage participants or voters. The goal is to prevent the same user from appearing in multiple dropdown lists once they have been selected. To achieve this ...

Creating a D3js line chart by inputting JSON data with d3.json

Since delving into the world of D3.js, I have encountered some challenges. Here is a summary of what I have experimented with so far: Below is my JavaScript code: d3.json("../js/sample2.json", function(data) { var canvas = d3.select("body").append("s ...

Dimensions of a typedef'd 2D Array

Consider a user-defined 2D array: typedef float Matrix3x3[3][3]; If you want to calculate the total number of float elements in Matrix3x3, one might think the following code would work: sizeof(Matrix3x3) / sizeof(**Matrix3x3) However, it is not possibl ...

Update a portion of a hyperlink using jQuery

Currently, I am utilizing Ransack for sorting purposes. However, I encountered an issue when attempting to modify the sorting links in cases where both search and sorting functionalities are implemented using AJAX. As a result, I have taken it upon myself ...

"Oops, Looks like we've hit a 404 | Uh-oh,

After setting up my page routing using react-router v5, everything was functioning perfectly. Clicking on a link would direct me to the desired page without any issues. However, upon reloading the page, I encountered a "404 | Page Not Found" error. import ...

The $http function in AngularJS consistently returns undefined instead of the expected value

var result = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null, function (response, status, headers, config) { // I can see `true` if I alert(response); here // I want to return the contents of ...

Unable to retrieve PHP data using AJAX

Index.html → <form> <div class="form-group"> <!-- <input type="text" id="name" class="form-control" placeholder="Enter Name"> --> </div> <div ...

What is the process for obtaining jsonencode data in a Laravel application?

server control public function room_details(Request $request) { $data['room_number'] = $request->id; $data['result_set'] = Rooms::find($request->id); echo $data['result_set']; return view('room ...

The process to reset a component's state when using router.push to navigate back to the same component

I am facing an issue with resetting the state on router.push in my project. I have a header component that includes a search option. When a user searches for something, router.push redirects them to '/search/${search}'. On the search page (SSR), ...

Switching around identifiers and subscripts to access built-in arrays and initializer lists for multi-dimensional arrays

I am curious about a specific syntax and how it works. Could someone provide insight into its potential usefulness or the mechanism behind its validity? For example, if you have: char A[] {'a', 'b', 'c'}; then 2[A] == &apos ...

The aggregation pipeline in nodeJS with mongoDB is failing to return any results, returning an empty array instead

Currently, I am enrolled in Jonas Schmeddtman's Node.js course where I am working on developing a tour App. However, I have encountered an issue where sending a request via Postman on the specified route results in an empty array instead of the expect ...

Leveraging arrays generated from two separate MySQL queries for dual selection functionality with JavaScript

I have successfully populated the first HTML select with results from the first query. Now, I would like to store the results from the second query in either a Json file or XML and then use plain javascript (not jQuery) to populate the second HTML select ...

The new method of calling datatable no longer supports the use of jquery's on('click') function

After updating my approach to creating a datatable in order to facilitate dynamic column generation, I included a column meant for revealing detailed information. function format (d) { console.log(d); var output = '' ; $.eac ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

Issue with ng-cloak not resolving flicker on button in Chromium; strangely, ng-cloak CSS doesn't apply as expected

Here is a snippet of my HTML code: <button type="button" class="btn btn-primary ng-cloak" ng-click="ctrl.add(ctrl.userProfile.username)" ng-hide="ctrl.userProfile.added">Add</button> The code above is a part of the larger HTML document shown ...

What is the best way to create a JavaScript object specifically for an HTML form?

I am looking to create a versatile object that can handle all the necessary actions for my form, such as validation and submission. My goal is to use JavaScript to streamline these processes and avoid repetitive code in the global namespace. I need to crea ...

Toggle the frequently asked questions feature by including a selector

I am trying to create a toggle FAQ feature. When the user clicks on the "+" symbol, it should expand and collapse the answer. I want to implement toggling functionality when clicking both the "+" symbol and the question title. Question: How can I toggl ...

Greasemonkey script causing interference with other website scripts

Although my Greasemonkey script is functioning exactly as I want it to, it seems to be blocking the website's own JavaScripts. As a result, these scripts are no longer working. I have been using the incredibly useful waitForKeyElements() function to ...