How can I display all values in Meteor Blaze by iterating through a mongo cursor?

Can someone please guide me in the right direction? I have an application that uploads a CSV file to MongoDB and then displays it within the Meteor framework. I am facing an issue where I am subscribing to the data in the Template.onCreated function, but I am unable to iterate through the MongoDB cursor in the Template.helper to display the values in a table.

Template.table.onCreated(function() {
  Template.instance().subscribe('contacts');
});

Template.table.helpers({
  contact() {
    var contactCursor = Contacts.find();
    return contactCursor;
  }
});

I have attempted to use cursor.fetch() and map methods, but it either does not render anything or crashes Chrome. The table structure I have tried to implement is:

    <tr>
      <td>
        {{#each contact}}
          {{contact}}
        {{/each}}
      </td>
    </tr>

However, all I see in the table is:

[object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object]

or sometimes nothing at all. I am struggling to understand how to iterate through the cursor properly. The structure of the MongoDB collection is as follows:

{ "_id" : "Mzb6a9uh3948vw", "contact" : [ { "emailAddress" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f89f949d96b89d80999588994">[email protected]</a>", "someContact" : "No", "creationDate" : "N/A", "bounceBack" : "N/A", "unsubscribed" : "N/A" } ] }

I am aiming to display the data in the table in the following format:

        {{#each cursor}}
          {{emailAddress}}
          {{someContact}}
          {{createdDate}}
          {{bounceBack}}
          {{unsubscribed}}
        {{/each}}

Any assistance would be greatly appreciated. I am new to the Meteor/Blaze environment and struggling to figure out the correct way to iterate through the cursor. Thank you!

Answer №1

Check out this code snippet:

//contact helper function
contacts() {
    var contactCursor = Contacts.find();
    return contactCursor;
}

//display contacts in HTML
{{#each contacts}} 
    {{#each contact}}
        <p>email: {{emailAddress}</p>
    {{/each}}
{{/each}}

Do you wonder why the data structure is like this?

{ "_id" : "Mzb6a9uh3948vw", 
"contact" : [ { "emailAddress" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="583f343d36183d20393528343d763b3735375c393f">[email protected]</a>", "someContact" : "No", "creationDate" : "N/A", "bounceBack" : "N/A", "unsubscribed" : "N/A" } ] 
}

Wouldn't it be simpler like this?

"_id" : "Mzb6a9uh3948vw", 
"emailAddress" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88efe4ede6c8edf0e9e5f8e4eda6ebe7e5">[email protected]</a>", 
"someContact" : "No",
//additional fields

Then you can access the data like

{{emailAddress}} //outputs "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec9c2cbc0eecbd6cfc3dec2cb80cdc1c3">[email protected]</a>"
, {{someContact}} //outputs "No"

UPDATE:

You can save individual contacts with a relevant user ID and retrieve them like this:

Contacts.find({userId: Meteor.userId()});

Alternatively, you can handle this in your publication, which is usually the preferred method.

Answer №2

Your contact helper retrieves a cursor containing objects with a nested array also named contact. It is necessary to iterate over this nested array as well:

{{#each contact}}
  id: {{_id}}
  {{#each this.contact}}
    email address: {{emailAddress}}
    some contact?: {{someContact}}
    creation date: {{creationdate}}
    bounce back: {{bounceBack}}
    unsubscribed?: {{unsubscribed}}
  {{/each}}
{{/each}}

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

Having trouble locating a method in $scope following angular $compile

Apologies for the simple question, I am a beginner in AngularJS and front-end development. I am attempting to create a modal using bootbox as shown below: In Service: function _modalData(){ let element = "<div onclick=\"saveSelecti ...

Executing a script in the event that a MongoDB database is not present

Currently, I am managing a Vagrant instance where a check is performed upon booting the VM to verify if a MongoDB database exists. If the database is not found, a Grunt task is executed to create it. The issue arises when the database is not present, as th ...

What is the best way to conceal the initial column using jquery?

Is there a way to automatically hide the first column of data as it loads from a csv file using jquery and AJAX? I know you can do this using onclick function, but I prefer to have it automatically hidden. How can I achieve this? Below is the sample CSV d ...

After an ajax request, the Jquery hover effects are no longer functional

On my website, I have implemented ajax calls to filter product results and apply effects. However, the effects on these products seem to stop working after the ajax call is completed. Located at the bottom of the page's code is the following script: ...

Run the function multiple times by substituting a portion of the argument in a sequential

I am facing a challenge with a method (exampleObj.method) that requires arguments of an object and a function. The code snippet is as follows: exampleObj.method({ name1: 'string1', name2: 'string2', name3: &apos ...

Execute Javascript to simultaneously open various links in a single action (not using popups)

I am looking to open multiple URLs with a single click event that also redirects to a specified URL. I have attempted this, but it doesn't seem to be working as intended. Here is the HTML code: <a id="mybutton" href="http://example.net/quote" onc ...

Can someone guide me on leveraging MongoDB aggregation match with an array in order to implement pagination effectively?

Within my database, I have two main collections: User and Post. The structure of the User collection is as follows: { "_id": "ObjectID(...)", "name": "...", "gender": "...", "followers": [ObjectID(...), ObjectID(...), ObjectID(...), ....], "follo ...

Showing the values of two distinct select boxes in a URL

Here are both select boxes, the goal is to display selected values from both in the URL. This can be achieved by displaying them like this: e.g www.example.com#135+#140 OR www.example.com#135&140 (The order of values doesn't matter as long as bot ...

Tips for creating a reusable function in React.js?

I have a script that executes on input focus and passes certain values based on a specific logic. I would like to reuse this script for multiple input fields that trigger the focus event. How can I accomplish this? This is my current script: <input ...

The contents of the multi-level navigation are automatically shown as the page loads

I've implemented a multilevel dropdown menu on my website using a plugin, and it works as expected. However, there's an issue where the contents of the dropdown menu display for a brief moment while the page is loading. I tried adjusting the posi ...

Tips for managing CSS/style conflicts in JavaScript/AngularJS applications

I am new to AngularJS and I have a requirement to assign CSS properties to a component at the JavaScript file level. When I debug my code after applying the CSS styles to the component, I can see that all the applied CSS properties are behaving as expected ...

What is the most effective method for determining if an object contains a particular property?

Can anyone advise on the best approach to check if an ajax response object has a specific property? I've done some research and it seems there are various methods to do this. One way is: if(ajaxResponse.hasOwnProperty('someProperty')){ ...

Data retrieval seems to be encountering issues in Firefox and IE9, whereas Chrome and Safari are functioning without any problems

I am using the following method function callCommentservice() { try { // Comment Service Url var getCommentServiceUrl = self.commentsServiceUrl + self.getRating + "tenantId=" + self.tenantId + "&ratedObjectTypeId=" + sel ...

Display the closest locations on the Google Maps interface

I am currently working on a project that involves integrating Google Maps. The project includes storing hospital addresses (in longitude and latitude) in a database. However, I need assistance in displaying the nearest hospital from my current location. I ...

How to manage multiple items within a single MUI/React TextField

Recently diving into the world of JS, React, and MUI, I find myself faced with a challenge involving a MUI TextField that is supposed to handle multiple values. For example: 1*10 5*50 13*250 5*50 1*10 3*33.33 4*25 3*33.33 All on a single line. These ...

What types of HTML are compatible with SweetAlert?

I am exploring the HTML elements that can be used with the SweetAlert alert function (). It seems that headings like h1, h2, etc. and strong tags are allowed, but when I tried to add inline styles like style="color:blue;", the alert stopped working. The v ...

Problem with Ajax causing full-page reload

I currently have a webpage that utilizes JqueryUI-Mobile (specifically listview) in conjunction with PHP and some Ajax code. When the page loads initially, it displays a list generated from a MySQL DB. I want this list to refresh itself periodically witho ...

Issues with CSS Modules not applying styles in next.js 13 version

Employing next.js 13.1.1 along with /app Previously, I had been handling all of my styles using a global.css, however, I am now attempting to transition them into CSS Modules. Within my root layout.js, there is a Header component that is imported from ./ ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...