cmee
cmee

Reputation: 45

Creating a simple filter in Meteor

I would like to filter a collection of posts based on a list that various posts belong to. I have a dropdown that allows users to select the list but cannot figure out how to only show posts that are associated with that list.

Each post right now has a list name and id that is being saved with it - and I am able to present the available lists.

All I need to do right now is a simple filter so a user can basically "view" only posts for a given list.

Here's where I'm at - if I could pass an id from the select into postlistid - just haven't figured out how to do this. I tried using a variable and getting the value in an event change on the list passed through to the helper but again not quite connecting the dots.

    Template.userPostsFiltered.helpers({
      userfilteredposts: function() {
      var currentUser = Meteor.userId();
          return Posts.find({userId: currentUser, postlistid: { $exists : true }}, {}, {sort: {date: -1}},{reactive:true});
     }
});

Thanks

Upvotes: 1

Views: 2387

Answers (1)

David Weldon
David Weldon

Reputation: 64312

Here's a complete working example:

posts.html

<head>
  <title>test</title>
</head>

<body>
  {{> userPosts}}
</body>

<template name="userPosts">
  <h2>Post Lists</h2>
  <select>
    {{#each postLists}}
      <option value="{{_id}}">{{name}}</option>
    {{/each}}
  </select>

  <h2>Filtered Posts</h2>
  <ul>
  {{#each filteredPosts}}
    <li>{{name}}</li>
  {{/each}}
  </ul>
</template>

posts.js

Posts = new Mongo.Collection(null);
PostLists = new Mongo.Collection(null);

if (Meteor.isClient) {
  Meteor.startup(function () {
    var pl1 = PostLists.insert({name: 'List 1'});
    var pl2 = PostLists.insert({name: 'List 2'});
    var pl3 = PostLists.insert({name: 'List 3'});

    Posts.insert({postListId: pl1, name: 'A'});
    Posts.insert({postListId: pl1, name: 'B'});

    Posts.insert({postListId: pl2, name: 'C'});
    Posts.insert({postListId: pl2, name: 'D'});

    Posts.insert({postListId: pl3, name: 'E'});
    Posts.insert({postListId: pl3, name: 'F'});
  });

  Template.userPosts.helpers({
    postLists: function () {
      return PostLists.find();
    },

    filteredPosts: function () {
      var postListId = Session.get('selectedPostListId');
      return Posts.find({postListId: postListId});
    }
  });

  Template.userPosts.events({
    'change select': function (e) {
      var postListId = $(e.currentTarget).val();
      Session.set('selectedPostListId', postListId);
    }
  });
}

Upvotes: 3

Related Questions