Using Meteor: The ultimate guide to filtering data with a session variable

I have three buttons that display different types of information

  1. View all (i.e., news AND events)
  2. news only
  3. events only

Status: Filtering ONLY news OR events works. But how can I view both?

My problem lies in writing a MongoDB query in combination with a session variable. The commented out lines show a failed attempt. In my unsuccessful approach, I tried to include more in the session value by adding the word "type." However, this caused all queries to break.

Here is my js-file:

Template.newsEvents.helpers({
  newsEventsData: function () {
    // return NewsEvents.find({Session.get('newsEventsView')}, {sort: {createdAt: -1}, limit: 3});
    return NewsEvents.find({type: Session.get('newsEventsView')}, {sort: {createdAt: -1}, limit: 3});
  }
});

Template.newsEvents.events({
    'click #js-seeAll': function (evt, tpl) {
        //Session.set('newsEventsView', '$or: [ { type: "news" }, { type: "event" } ]');

    },
    'click #js-seeNews': function (evt, tpl) {
        //Session.set('newsEventsView', 'type: "news"');
        Session.set('newsEventsView', 'news');
    },
    'click #js-seeEvents': function (evt, tpl) {
        //Session.set('newsEventsView', 'type: "event"');
        Session.set('newsEventsView', 'event');
    }
});

This is how my JSON file looks like:

{
    "_id" : "7sLK32LdoLv4NmtMJ",
    "title" : "3rd News",
    "description" : "Some News",
    "type" : "news",
    "createdAt" : ISODate("2016-01-18T11:23:36.412Z")
}

Any assistance would be greatly appreciated.

Answer №1

To filter messages based on their type, consider using the $in clause with an array stored in a Session variable called 'newsEventsView'. This approach allows users to selectively view certain types of messages by updating the Session variable when needed.

Template.newsEvents.events({
    'click #js-seeAll': function (evt, tpl) {
        Session.set('newsEventsView', [ "news", "event" ]);
    }
});

Template.newsEvents.helpers({
    newsEventsData: function () {
        return NewsEvents.find({
            type: {
                $in: Session.get('newsEventsView')
            }, 
            sort: {
                createdAt: -1
            }, 
            limit: 3
        });
    }
});

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

difficulty with displaying the following image using jquery

I have referenced this site http://jsfiddle.net/8FMsH/1/ //html $(".rightArrow").on('click',function(){ imageClicked.closest('.images .os').next().find('img').trigger('click'); }); However, the code is not working ...

Facing difficulty in accessing mongoose schema static method in TypeScript

I am currently facing an issue where I have a method called "findByToken()" defined in the model and implemented as a static method in the userSchema. However, in another part of my application, I am unable to access the method using: User.findByToken(tok ...

Transforming an HTML and Javascript Project into a Standalone Application

Currently, I am engaged in a side project to enhance my skills in HTML/CSS/JavaScript. I have been using Aptana as my primary tool for coding, and it is configured to run smoothly in a browser environment. Specifically, the project I am working on is a te ...

Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a ...

error: local server did not return any data

I am currently using PHP on a Linux machine. In my HTML code, I have set up an AJAX request to the local Apache server (check http://localhost), with the intention of displaying the data from the server on the screen. However, for some reason, nothing is b ...

What significance does comparing two arrays hold in the realm of Javascript?

While working in my node.js REPL, I have created 4 arrays: a = [1,2,3], b=[], c=[4,5], d=null (although d is not actually an array). I decided to compare them directly like this: > b = [] [] > a > b true > b > a false > a > c false & ...

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

Retrieving User Activity Reports for a specified set of users within G Suite

I am currently attempting to utilize the Admin SDK Reports Service to retrieve the latest login time and other data for a specific set of 20 users. Due to the large size of the domain, it is not practical to fetch data for the entire domain and then filter ...

Building a Subscription Service with Express.js and MongoDB

Hello, I'm a beginner with express.js and I'm currently working on a project. The project involves a shop owner creating different plans with varying prices. My goal is to allow users to subscribe to a plan only after making a payment. Can someon ...

What is the syntax for assigning a variable name as "i" within a for loop in JavaScript?

Location data results include latitude and longitude coordinates. for(i=0; i<results.length ; i++ ){ var (marker + i) = new google.maps.Marker({ position: results[i].geometry.location, map: map }); var (infowindow + i)= new google.maps.I ...

I'm trying to retrieve the InsertedId from a MongoDB document after it has been inserted, but unfortunately using the InsertedId method doesn't seem

Currently using ktor along with MongoDB for the backend of an android project. After inserting a document, the acknowledgment returns true. However, when attempting to retrieve the InsertedId, it shows as null despite being inserted successfully into the d ...

The delete button in the "Chip" component of React Material-UI is not functioning as expected

I'm having trouble with the "Chip" control and its "X" button functionality. Unlike the examples shown here: http://www.material-ui.com/#/components/chip Adding the "onRequestDelete" property does include the "X" button, but it doesn't respond t ...

What is the best way to structure this basic SQL schema within MongoDB?

For my college project, I need to develop a basic Java application that evaluates the performance of MySQL and MongoDB. The SQL schema consists of three tables: artist, album, and track. In this schema, there is the following relationship: each artist can ...

React App PWA ERROR: Service worker not registered to control the page and start_url

I am encountering an issue while building a progressive web app using Create React App. Lighthouse benchmarking results in an error, indicating that my PWA is not installable. Surprisingly, I face the same problem even when utilizing the official PWA templ ...

"The AJAX request triggers an internal 500 error whenever either a post or get request is

Whenever I attempt to submit a post or use the get method from my index.php file which calls Ajax_mysql.php through the Ajax function POST or GET, I encounter a frustrating Internal 500 error. The server doesn't provide any additional information abou ...

Sorting prices in descending order using Expedia API

Is there a way to arrange prices in descending order using the response.hotelList[i].lowRate? The provided code is as follows: success: function (response) { var bil = 1; var hotel_size = response.hotelList.length; $('#listD ...

Can you explain the distinction between setting abc.p as undefined versus deleting abc.p?

The variable abc is pointing to an object. What distinguishes abc.p = undefined from delete abc.p aside from their return values? ...

Can the parameters in a .slice() be customized within a v-for loop?

I am currently working with Laravel 8 and using blade syntax. The following code snippet is from a Vue component I created: <li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" v-if="comic.item_type === 'b&ap ...

Tips for accessing the value of the range slider in Bootstrap 5 while it is being slid

Is it possible to capture the value from a Bootstrap 5 slider while sliding? I want to continuously receive the value as I move the handle, rather than only getting the final value when I release the handle. Currently, I am using a Bootstrap 5 range slide ...