How to dynamically pass variables to MongoDB queries in a Meteor application

Starting a simple meteor app to search a database and running into some issues. I have an input box where the search query is obtained using the code below:

Template.search.events = {
'keydown input#search' : function (event) {
    if (event.which == 13) {
        var item = document.getElementById('search');
        Template.results.results(item.value)    
        //console.log(item);    
        item.value = '';
    }
}
}

The search query is then passed to another function which queries the mongodb to print the result in the template:

Template.results.results = function (item) {
return Products.find({sku: item});
}

However, it doesn't seem to find the item! When running the same query in Chrome's console or using a hardcoded value like {sku: "A2277"} it works fine. Even creating a new variable with a hardcoded value within the Template.results.results function works. What could be causing this issue?

Answer №1

Template helpers are intended to be called by the template itself, rather than directly by event handlers. Your code requests a query to be executed and returns a value without any connection to the template. Instead, it is advisable to utilize a session variable in this manner:

Template.results.results = function() {
  return Products.find({sku: Session.get('itemSku')});
};

In your event handler, you can then implement something like the following:

Template.search.events({
  'keydown input#search': function(event) {
    if (event.which === 13) {
      var $item = $('#search');
      Session.set('itemSku', $item.val());
      $item.val('');
    }
  }
});

It's worth noting that jQuery was used here to set/get the item values. Nevertheless, this action will define the session variable and trigger the results to be redrawn reactively.

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

Guide on repeatedly clicking the Cookie to enjoy Cookie Clicker on https://orteil.dashnet.org/cookieclicker/ with the help of Selenium and Python

I've been attempting to create a selenium program for playing Cookie Clicker, but I'm encountering some issues. Here's the code I have so far: from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains P ...

Sending JSON data from a Django view to a JavaScript function

I am trying to pass JSON data to JavaScript. I need the JSON structure to be like this: data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database ...

javascript display error message in innerHTML if passwords do not match

Hello, I found your code to be helpful but I am facing an issue. I want to display a message using innerHTML when the passwords do not match. I have been trying to implement this feature but it is not working for me. Below is my current code. Please provid ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Methods for bypassing a constructor in programming

I am working on a code where I need to define a class called programmer that inherits from the employee class. The employee class constructor should have 4 parameters, and the programmer class constructor needs to have 5 parameters - 4 from the employee c ...

Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text. https://i.sstatic.net/iTKoo.jp ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

Ways to retrieve the year and month from a given date

https://i.sstatic.net/EZy4e.pngI'm working with two forms. Form1 has an input field for a date and a button to validate the input. When the user clicks on the validate button, I want the year of the date to appear in the "Year" cells and the month to ...

Unable to successfully export ExpressJS routes to an external file when targeting the root path

I am seeking a way to organize my routes by exporting them into external files. Currently, all routes except the root route are functioning correctly: localhost/login -> "Login page" localhost/ -> empty server.js: // SERVER SETUP ============= v ...

Automatically unselect the "initially selected item" once two items have been selected in Material UI

As someone new to web development, I'm struggling with a specific task. Here is the issue at hand: I have three checkboxes. If box1 and then box2 are selected, they should be marked. However, if box3 is then selected, box1 should automatically unchec ...

Ways to implement a single AJAX function for multiple buttons

I need to call the same AJAX function for multiple buttons. Please assist with the code provided below. This particular code will create buttons and upon clicking on them, it displays details... please assist with resolving this issue. The code generated ...

`Dealing with Java Servlet Exception in Kendo UI Environment`

I am facing an issue with displaying date in my Kendo UI grid. The data is coming from a Java servlet, and I have set the status code to 500 whenever an error occurs. Although I can see the error on the console, I am unable to handle it in JavaScript. My g ...

Tips for sending a MySQL parameter

Hey there, I need some help with the trigger setup I have: CREATE TRIGGER `update` AFTER UPDATE ON `table 1` FOR EACH ROW INSERT INTO table 2 ( Id, Revision, Purpose, Change ) VALUES ( OLD.Id, OLD.Revision, OLD.Purpose, @purpose_change /* user variable ...

Javascript in Chrome can be used to initiate and conclude profiling

Is there a way to activate the CPU Profiler in the Chrome developer window using a Javascript call? For example: chrome.cpuprofiler.start(); //perform intensive operation chrome.cpuprofiler.stop(); Currently, my only option is to manually click on "s ...

What is preventing this PHP script from functioning properly with Google Maps?

I'm having trouble understanding why this PHP script isn't generating the specified map on the HTML page. Any suggestions? <!doctype html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-sc ...

Obtaining Distinct Values in AngularJS Using ng-option

My table contains the following data: info = [ {id: 1, name: 'Manchester United', type: 'Soccer', featured: true, country: 'England'}, {id: 2, name: 'Manchester City', type: 'Soccer', featured: false, ...

Calculating the total of two fields within the same schema and storing the outcome in a separate schema in MongoDB

Given two schemas, I need to calculate the scores of player1 and player2 to save in another schema. Note: Both players are in the same schema. How can I apply aggregation? Below is a list of steps to follow for calculating the results: a) When creating ...

The shared module for next/router is not found in the shared scope default within Next.js and @module-federation/nextjs-mf

I am working on a JavaScript Turbo repo with a host app that has the following configuration in its next.config.js: const { NextFederationPlugin } = require("@module-federation/nextjs-mf"); const nextConfig = { reactStrictMode: true, ...

Is there a way to send the value of a jQuery variable to be retrieved by a PHP $_POST method?

I have successfully managed to gather all the values from a multi-select form into a single delimited variable. However, I am struggling to pass this 'output' value to my PHP script utilizing the $_POST array. How can I ensure that the 'outp ...

Rows in a table will not decrease when added anew

On a page that allows adding and deleting rows from a table of input fields, the following code functions properly for existing fields. However, when attempting to add new rows and delete them in a sequential manner that requires replacing the ID and name ...