"Empower your app with the dynamic combination of Meteor Publish and

Consider the scenario below:

In my client application, I have created a complex filter stored in a custom reactive object named currentFilter.

The method currentFilter.buildQuery() is used to generate the query object for MongoDB database.

Due to the large volume of data stored in the MongoDB database on the server, I prefer to perform data filtering on the server side and only send relevant data to the client.

Here is the code snippet:

//CLIENT

// file = a.html

<template name="myTemplate">
  {{data}}
</template>

//file = a.js

cbs = new Mongo.Collection('cbsLoc');

Template.myTemplate.helpers({

    data: function () {
        Tracker.autorun(function () {
            Meteor.subscribe('cbsLoc',currentFilter.buildQuery())

        });

        return cbs.find()    // (a)
    }
})

//SERVER

Meteor.publish('cbsLoc', function(filter) {
    return cbs.find(filter)
});

The cbs.find() retrieves data to populate a table. Unfortunately, it doesn't show any data. Although the data is sent to the client, it's not being displayed in the DOM.

However, if I modify line (a) to cbs.find().fetch(), it works perfectly fine and displays the data in the DOM.

I would greatly appreciate any assistance with this issue.

Answer №1

I decided to place this content in an answer rather than a comment because it contains some code that may be challenging to read.

Upon pondering the issue, it seems that the cursor might not be ready when the template is displayed. I recall that with fetch() in Meteor, everything will wait until all data has arrived.

You could try implementing some defensive coding like so:

data: function () {
   Tracker.autorun(function () {
       Meteor.subscribe('cbsLoc',currentFilter.buildQuery())
   });
   var cursor = cbs.find();
   if(cursor) 
       return cbs.find()    // (a)
}

If this approach does not yield results, another option could be to move the data retrieval process to the router (assuming you are using iron-router). This way, you can incorporate the subscribe portion within the waitOn() or subscriptions() function, which is typically where subscriptions belong.

Answer №2

Below is the solution I came up with.

I made a change by moving the subscription into an onCreated() callback. Here is my final code:

//CLIENT

// file = a.html

<template name="myTemplate">

    {{#if Template.subscriptionsReady}}
        {{> reactiveTable class="table table-bordered table-hover table-responsive" collection=cbListings settings=settings}}
    {{else}}
        {{>loading}}
    {{/if}}

</template>

//file = a.js

cbs = new Mongo.Collection('cbsLoc');

Template.myTemplate.onCreated(function () {
    var self = this;

    self.autorun(function () {

        self.subscribe('cbs', currFilter.buildQuery());

    });

    self.cbListings = function(){
        return cbs.find();
    }

});

Template.myTemplate.helpers({

    cbListings: function() {

        return Template.instance().cbListings();
    }
});

//SERVER

Meteor.publish('cbsLoc', function(filter) {
    return cbs.find(filter)
});

Credit goes to David Weldon and mwarren for guiding me in the right direction.

This solution was based on information from the official Meteor docs and this blog post.

It's worth noting that this pattern only works with

{{#if Template.subscriptionsReady}}
as shown below:

{{#if Template.subscriptionsReady}}
    {{> reactiveTable class="table table-bordered table-hover table-responsive" collection=cbListings settings=settings}}
{{else}}
    {{>loading}}
{{/if}}

The relationship between the onCreated and helper callbacks can be a bit confusing:

1)

Initially, self.cbListings is null on page load, which makes sense.

2)

Later on, the helper creates cbListings, but returns a reference to itself using Template.instance().cbListings(). This may seem strange, so what exactly is happening here?

Additionally, why doesn't it throw an error when trying to access Template.instance().cbListings() before it actually exists? When checking inside the onCreated callback, the output is undefined, yet inside self.cbListings it shows as function().

3)

Even though the onCreated callback runs only once, somehow Template.subscriptionsReady manages to execute

self.cbListings = function(){return cbs.find()}
after cbListings is created by the helper. How does this work?

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

Extracting data from websites based on specific criteria

I'm currently extracting data from the following website: , specifically targeting span.summary-hero-name. Below is the code I am using for this task: scrapeIt("https://masteroverwatch.com/profile/pc/us/calvin-1337", { title: "span.summary-hero-na ...

Bootstrap 4 - DropDown option - Element is positioned above the navigation bar

Currently facing an issue with the DropDown menu. Whenever I add padding to the DropDown menu (class - drop_link), it ends up pushing the entire element over the <nav>. I'm unsure of how to prevent this from occurring. I attempted to disable som ...

Only the first iteration of a for loop is updating the array

This particular script is designed to work with an array of objects that are structured in the following way: {html:whatever number:number value}. function Org(data){ //array of objects var Data=data; for(var i=0; i<Data.length; i++){ var nums=[]; ...

Capturing and Receiving Voice Audio in DiscordJSv14

Currently, I am developing a Discord bot in JS using DiscordJSv14 and I want the bot to extract audio from a voice chat and forward it to another bot, functioning like a spy or eavesdropper bot. Although I have successfully connected the bot to the voice ...

react-native-track-player failing to play song requested from Express server

I set up an expressjs server with a 'songs' route that serves .mp3 files. Here is the code for the Songs Route: import express from "express" const path = require("path") const router = express.Router() ... router.get(" ...

Modify vanilla JavaScript carousel for compatibility with Internet Explorer

I am currently in the process of creating a website that incorporates a carousel similar to the one found at the following link: https://codepen.io/queflojera/pen/RwwLbEY?editors=1010 At the moment, the carousel functions smoothly on opera, chrome, edge ...

Tips for optimizing the performance of a React application when deploying it to Azure

After successfully deploying my application to Azure Web Apps, I encountered an issue with the response time. The client is located in one folder and the server in another. When accessing the application at , it takes approximately 15 seconds for the page ...

Encountering a reference error message in Xcode indicating that a certain object has not been defined

In the process of developing parse cloud code to interact with eBay, fetch JSON data containing item results, and extract the top two categories for storage in an array, I encountered an issue. The query sent to eBay is determined by user input in the item ...

What is the best way to display JSON data in a readable format?

I received a JSON file with the following structure: { "data":{ "uuid":"123", "name":"TestData", "alias":null, "created_at":"2021-03-17T11:57:29.000000Z&q ...

What is the proper method to trigger a re-render of a React functional component with the useEffect

Within my top-level component, I am utilizing a library to determine if a user’s browser is in light or dark mode. This information is then used to set the theme for the application, which includes HTML Canvas elements (it's crucial to note that the ...

Is VueAxios compatible with the Vue composition API?

Currently, I find myself in main.js where I am importing vue-axios Main.js import { createApp } from 'vue'; import axios from 'axios'; import VueAxios from 'vue-axios'; import App from './App.vue'; const app = crea ...

NodeJS and Express server is having trouble accessing the linked JavaScript file(s) from the HTML document

I'm facing a challenge with my web hosting server on AWS while using express.js. I have encountered the following error: root@ip(censored):/home/ubuntu/(censored)# /home/ubuntu/(censored)/routes/index.js:15 $(document).ready(function() { ^ Referen ...

Adding auth0 authentication to a Next.js 13 application: A step-by-step guide

Currently, I am using a nextjs 12 application and set up auth0 as my authentication provider by following the guidelines provided here: https://auth0.com/docs/quickstart/webapp/nextjs/interactive. However, I am now looking to upgrade my application to next ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

I was surprised by how Await behaved in if-else statements, it was not what

let metadata = []; allNFTs.map(async (e) => { if (e.metadata) { metadata.push(JSON.parse(e.metadata).attributes); } else { let config = { method: "get", url: `http://localhost:3000/api/fetch ...

Utilizing Custom HTTP Headers in Angular 2 to Enhance Request Handling

Within my Angular 2 project, I am implementing the use of Http (@angular/http) to communicate with my API. In order for these requests to be successful, specific headers, including a JWT header, must be included in each API request. My goal is to have an ...

Differences Between ES5 and ES6 in Dealing with Arrays in JavaScript

I need assistance with converting the code snippet below as I suspect it is related to an ES5/ES6 compatibility issue. Any help would be highly appreciated. this.rows = Array.from(Array(Math.ceil(this.subCategoryModels.length / 3)).keys()); Upon attempti ...

The HTML element update event was not triggered due to the excessive load of a JavaScript function

I am currently running a JavaScript function that is quite CPU intensive. To provide visual feedback to users when it starts and stops, I am attempting to display a badge on the webpage. Below is the code snippet: function updateView() { console.log(1 ...

Evaluating database function integration with Jest testing framework

Just starting out with Jest and testing my code in general. I want to test a function that pulls data from a mongodb database using mongoose. However, every time I run the test, all database calls within the function return null. What's the best appro ...