nurul
nurul

Reputation: 13

Meteor : create a search (filter) without using autopublish

I have a search facility in my project and I need to be able to publish results without using autopublish.

html

<template name="search">
  <form  id="searchform">
    <input type="text"  id="kategori" placeholder="Sila masukkan maklumat carian."/>
    <button>Carian</button>
  </form>
  <hr/>
  <h3>Maklumat</h3>
  <ol>
    {{#each profil}}
      <li>{{jenama}}</li>
    {{/each}}
  </ol>
</template>

js:

Template.search.events({
  "submit #searchform": function (e) {
    e.preventDefault();
    Session.set("kategori", e.target.text.value);
  }
});

Template.search.helpers({
  profil: function() {
    return Profil.find({
      kategori: Session.get('kategori'),
    });
  }
});

Upvotes: 0

Views: 38

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20226

You can simply subscribe to a filtered publication:

client:

Template.search.events({
  "submit #searchform": function (e) {
    e.preventDefault();
    Session.set("kategori", e.target.text.value);
    Meteor.subscribe('profiles',Session.get('kategori'));
  }
});

server:

Meteor.publish('profiles',function(kategori){
  return Profil.find({ kategori: kategori });
});

If you don't have any other subscriptions to the same collection you can also simplify your helper to:

Template.search.helpers({
    profil: function() {
      return Profil.find();
    }
});

Since the set of documents will be defined by your publication.

In practice though you usually use the same search in your helper as you do in the publication just to avoid documents from other publications showing up.

Upvotes: 1

Related Questions