Tips for using variable arguments in Meteor's find method

Why is the find query not returning any data when using the "qnum" variable argument as a value? Could it be due to the scope limitation of variables inside an object?

Quiz.js file

Questions = new Mongo.Collection("questions");

if (Meteor.isClient) {

  var qnum = 1;

  Template.question.events({

    "click #submit-btn": function (event, template) {
      //Increase question number each time user clicks on submit button to load next question
      qnum += 1;
    }

  });


  Template.body.helpers({
    questions: function (qnum) {
      return Questions.find({qnum: qnum});
    }
  });
}

Quiz.html file

<div class="quiz">
    <div class="score-board">
        {{#each questions}}
            {{> question}}
        {{/each}}
    </div>
</div>
</body>

<template name="question">
    <div class="qa-wrapper" id="{{qnum}}">
        <div class="questions">{{title}}</div>
        <div class="options">
                {{#each options}}
                <input type="checkbox" name="{{this}}"/>{{this}} <br />
                {{/each}}
            <button id="submit-btn">Submit</button>
        </div>
    </div>
</template>

Questions db collection

{ "_id" : ObjectId("55a207a21c4dbe14cf9837c7"), "qnum" : 1, "title" : "Question 1", "options" : [ "A", "B", "C", "D" ] }
{ "_id" : ObjectId("55a207b31c4dbe14cf9837c8"), "qnum" : 2, "title" : "Question 2", "options" : [ "A", "B", "C", "D" ] }

Answer №1

It seems like there might be a mismatch in the way you're passing arguments to your template helper. When setting up an argument for questions(qnum), it's expecting one, but in the {{#each questions}} section, you're not passing anything. Try removing the qnum in the template helper definition so that it looks like this:

Template.body.helpers({
  questions: function () {
    return Questions.find({qnum: qnum});
  }
});

This is untested, so please let me know if it works.

If you want your helper to rerun on button click, you'll need to make the query parameter (qnum) reactive. One option is to store the value of qnum in a Session variable.

Session.set("qnum", qnum)

Then, in the template helper query:

return Questions.find({qnum: Session.get("qnum") });

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

Property of a general object

I am working with an Interface export interface ChartDataResponseI { consumption: string generation: string measure_name: string point_delivery_number: string self_coverage: string time: string } My goal is to create a generic object property ...

Error occurred when sending form data while uploading a file

Upon trying to upload a file using the formData.append(key, value);, an error message is displayed in the value section: The argument of type 'unknown' cannot be assigned to a parameter of type 'string | Blob'. Type '{}' is ...

Using interpolation brackets in Angular2 for variables instead of dots

I'm curious if Angular2 has a feature similar to the bracket notation in Javascript that allows you to use variables to select an object property, or if there is another method to achieve the same functionality. Here is the code snippet for reference ...

Utilizing JavaScript to showcase information retrieved from the database

After implementing this code example for a cascaded drop-down menu, I would like to incorporate the names of individuals residing in a specific city. How can I achieve this functionality once a city is selected? Demo link: Complete code snippet below: ...

Adding a sign at the center of a map in React-Leaflet

One of the features I added to the map is a center indicator sign. <MapContainer fullscreenControl={true} center={center} zoom={18} maxNativeZoom = {22} maxZoom={22} classNa ...

The sorting feature for columns seems to be malfunctioning in Bootstrap 5

I have utilized bootstrap 5 to create a table, but I am facing an issue when trying to sort the first column as there is no change reflected. Below is how my table is structured: The structure of the table is as follows: <table class="table" ...

Tips for utilizing the switch toggle based on conditions in the render method of ReactJS

I'm diving into the world of React JS for the first time. I have two objects, taskData and taskDatafilter, that I need to render based on a specific condition. The challenge is to toggle between rendering taskData and taskDatafilter depending on the s ...

Struggling with deploying on AWS-EC2 using mup

Currently, I am in the process of deploying a meteor-react-app on Amazon Web Services. When I try to set up using Mup, the following results are displayed: Started TaskList: Setup Docker [54.69.xxx.xxx] - Setting up Docker [54.69.xxx.xxx] - Setting up Doc ...

Entwine words around an immovable partition

Is it possible to create an HTML element that remains fixed in place even as the content on the webpage changes, with everything else adjusting around it? I am looking to add a continuous line that spans across a dynamic webpage. No matter how much conten ...

Is there a way to directly access the React component that was clicked?

I'm looking to dynamically change the class of a component when clicked. By using state to create a new component with properties such as name and done (initiated as false), which are then added to the todos array, I want to find out how to identify t ...

Is the confirmation window not showing up on the active tab in Chrome Extension? It only seems to appear on the popup.html tab

I have created a Chrome extension for an e-gym that is designed to prompt a confirm window after every hour of using the Chrome browser. The issue I am facing is that the confirm window only appears on popup.html. I want to activate my extension so that it ...

Update the controller variable value when there is a change in the isolate scope directive

When using two-way binding, represented by =, in a directive, it allows passing a controller's value into the directive. But how can one pass a change made in the isolated directive back to the controller? For instance, let's say there is a form ...

Received an error while attempting to install react-router-dom

I keep encountering this error message whenever I try to install react-router-dom using NPM in VS Code: https://i.sstatic.net/hFshb.png npm ERR! Unexpected end of JSON input while parsing near '...stack-launcher":"^1.0' npm ERR! You can find ...

Vue.js component function "not instantiated within the object"

I recently started learning vue.js and decided to use vue-cli to set up a new project. As I was working on adding a method to a component, I encountered some issues: <template> <div> <div v-for="task in $state.settings.subtasks& ...

Can a node.js file be exported with a class that includes IPC hooks?

[Node.js v8.10.0] To keep things simple, let's break down this example into three scripts: parent.js, first.js, and second.js parent.js: 'use strict'; const path = require('path'); const {fork} = require('child_process&apo ...

Redirecting Firebase user authentication to a different webpage

I have developed a signupPage.html to validate a user and save information to the real-time database in Firebase with the following code: signUp_button.addEventListener('click', (e) => { var email = document.getElementById('email ...

Change the direction of the arrow on the button to point downwards once the menu has slid

After hovering over a button, an arrow is added to it. Upon clicking the button, a content div slides out within its wrapper by utilizing jQuery.slideToggle(). Following the slide out of the div, I aim to rotate the arrow in the button by 180 degrees to i ...

Step-by-Step Guide on Integrating MongoDB with Node-Red

I've encountered a flow https://i.sstatic.net/fCd7F.png whenever I attempt to deploy my flows, I receive the following message Error: More than 1 database name in URL My URL looks like this: mongodb+srv://username:<a href="/cdn-cgi/l/email-protec ...

Why is Devtools displaying an unusual numerical value in the console window?

Below is the code I am currently executing in the console. // Utilizing arrow functions without parameters for enhanced readability setTimeout( () => { console.log('Executed first'); setTimeout( () => { // More nested code cons ...

Error message: Unauthorized request error with the change.org JavaScript API

I am currently working on integrating the javascript API from change.org in order to retrieve all of my signed petitions for display on my source forge page. However, I am encountering an unauthorized request response from the change.org API. Despite tryi ...