Amir Rahbaran
Amir Rahbaran

Reputation: 2430

Meteor: How to filter data via a session variable

I have three button to show different type of information

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

Status: filtering ONLY news OR events works. But how to see both?

My issue is to write a mongodb query in combination with a session variable. Commented out lines show a failed approach. In my failed approach I tried to put more into the session value (i.e., adding the word type). However, this broke all queries.

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');
    }
});

My JSON file:

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

Any help appreciated.

Upvotes: 3

Views: 457

Answers (1)

Brett McLain
Brett McLain

Reputation: 2010

Use the $in clause and use an array for your Session variable 'newsEventsView'. I personally use this to filter messages based on their type. The types of the messages are added to an array that is stored as a Session variable and then passed to the $in clause. If the user doesn't want to see a certain type, they click a button which updates the Session variable. Your code would look like this:

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
            }
        });
    }
});

Upvotes: 2

Related Questions