Easiest way to find what you need with Meteor

As a newcomer to Meteor, I am attempting to incorporate a straightforward search feature into the website. While similar inquiries exist on Stack Overflow, none of the solutions have proven to be suitable for my situation.

The search bar is located in the header section. I have successfully subscribed and published a search. However, I am unclear about the next steps. How can I transmit the data from the search bar in order to query the database? What modifications need to be made to the header.js file to enable this database search functionality?

Here is the pertinent code:

header.js

Template.header.events({
  'submit form': function(e) {
    e.preventDefault();
    var query = $(e.target).find('[name=search]').val();

    ***** What should I add here? *****

    Router.go('searchResults');
  }
});

search_results.html

<template name="searchResults">
  <ul>
    {{#each questions}}
      <li>{{questionItems}}</li>
    {{/each}}
  </ul>
</template>

publications.js

Meteor.publish('searchResults', function(searchValue) {
  return Questions.find({
    body: {
      $regex: searchValue
    }
  });
});

router.js

Router.route('/searchResults', {
  name: 'searchResults',
  waitOn: function() {
    return [Meteor.subscribe('searchResults')];
  }
});

Answer №1

If you are utilizing a route to present the search outcomes, there is a straightforward method to pass the search term to the route. Here's an example:

Template.header.events({
  'submit form': function(e) {
    e.preventDefault();
    var keyword = $(e.target).find('[name=search]').val();
    Router.go('/searchResults/' + keyword);
  }
});

Then, in your route definition:

Router.route('/searchResults/:keyword', {
  name: 'searchResults',
  waitOn: function() {
    return [Meteor.subscribe('searchResults', this.params.keyword)];
  },
  data: function(){
    return Questions.find();
  }
});

Your publication already anticipates the query string, so everything should work smoothly!

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

Nuxt generate encountered a 500 error during execution

My Nuxt app pulls data from a Wordpress REST API, and when I run `nuxt generate`, approximately 100 pages are generated simultaneously. However, around 80% of the API calls made during this process fail with a status 500 error. https://i.sstatic.net/J8975 ...

Unlocking the power of executing Node.js functions with JavaScript

As I work on developing a Java web application, I need to access the environment variables of the user's machine when they open my site. Specifically, I require the username and domain information in order to leverage single sign-on technology. I&apos ...

Route.get() is looking for a callback function, but instead received an [object Promise]

Currently, I am in the process of developing a REST API using express and following the architecture outlined in this particular article. Essentially, the setup involves a router that calls a controller. Let me provide you with an example of how a call is ...

The loop is not functioning according to its design

http://codepen.io/abdulahhamzic/pen/aNexYj I have been attempting to implement a loop to display ten results on the screen, but it appears that there is an issue with my loop that I am unable to identify. In Mozilla, only one result is being shown on the ...

Registering components globally in Vue using the <script> tag allows for seamless integration

I'm currently diving into Vue and am interested in incorporating vue-tabs into my project. The guidelines for globally "installing" it are as follows: //in your app.js or a similar file // import Vue from 'vue'; // Already available imp ...

There is an issue with reading the model sent to the view during an ajax get request

Could use some assistance with the following: I am working on a function that is supposed to return two different entities, one as a return value and the other as a model. The return can be read, but the model cannot. $('.thumbnail').click(funct ...

Leveraging PHP with MongoDB across multiple subdomains

Source URL: http://www.example.com/ require_once('/home/site/www/vendor/autoload.php'); //using mongdb library $driverOptions = ["typeMap" => ['root' => 'array', 'document' => 'array']]; ...

Click the "Login" button using Jquery to gain access

Whenever I hit the Login button, a 500 Internal server error pops up in the console. Can someone guide me on the correct way to perform a POST request using jQuery? I would really appreciate any help. <button class="login100-form-btn" type=& ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Generate a custom JavaScript file designed for compatibility with multiple servers

I am looking to develop a JavaScript file that can be easily added to other websites, allowing them to access functions within my database using an API similar to the Facebook like button. This API should display the total likes and show which friends have ...

Duplicate the checkbox after it has been selected

I am attempting to create a function where a checkbox can be cloned when clicked, with the cloned checkbox starting off unchecked. Once the cloned checkbox is checked, it will then clone itself and the cycle continues. <section ...

Fuzzy Background to Enhance Your Bootstrap 5 Offcanvas Navigation Menu

Currently utilizing Bootstrap v5.2, I am endeavoring to replicate the image displayed in the link below: Blurry Sidebar Backdrop As per the MDN Documentation, backdrop-filter is intended for blurring the background of an element. .offcanvas-backdrop { ...

Improving performance of MongoDB aggregation queries: Enhancing $match, $lookup, and optimizing double $unwind operations

Imagine we have two sets of data: devices: This collection includes objects with fields such as name (string) and cards (array). Each item in the cards array has properties like model and slot. The cards are not separate entities; they are just nested dat ...

Learn how to access the media.navigator.enabled value of Firefox using Javascript

Lately, I've been working on a demo that utilizes getUserMedia() in Javascript to access the webcam of devices and display the video stream on an HTML5 canvas. In cases where browsers do not support getUserMedia(), I have implemented a fallback to a F ...

Using JavaScript to eliminate a folder from numerous image src attributes

I am facing a challenge on my website where I have multiple gallery categories that initially display smaller thumbnails. However, once the screen width goes below 1200px, I want to switch to displaying full-size images. The current setup of image display ...

Starting a function will result in the return of its name

const [data, updateData] = React.useState({ default: () => fetchData(), defaultTab: " }); useEffect(() => { console.log(data, 'current data values') }, [data]) The issue at hand is that whenever setState is called, the API call d ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

Are there methods to individually style components that have been generated through the .map() function?

My goal is to style each <Tuner /> component separately, which are being rendered for each item in the this.state.notes array using this.state.notes.map(). I want to position them individually on the page, but currently they all appear together. This ...

Steps for writing/appending the JSON object from a POST request to a JSON file

I'm looking to update a JSON file by adding a new element using data from a POST request. The process is mostly working, but I'm struggling with including the id in the data. Can anyone help me figure this out? I've tried various approaches ...

Transforming PHP MySQL date into a Javascript timestamp for plotting time series data with FLOT

Currently, I am in the process of developing a Flot JavaScript Time Series Line Graph that analyzes the registration activity of users over time. The graph depicts the number of users registering accounts against the timestamp of when the account was creat ...