Simple search method


#1

Hey guys I have this method in my collection

collections/fritkots.js

Fritkots.search = function(query) {
return Fritkots.find({
name: { $regex: RegExp.escape(query), $options: ‘i’ }
}, {
limit: 1
});
}

And in my template helpers I’m calling it like

search.js

Template.search.helpers({
searchResults: () => {
return Fritkots.search(Session.get(‘fritkotsSearchQuery’));

However I would like to just create a Meteor Method and the just do Meteor.call('search') but for some reason is not working. Could someone help ? Thanks

This is what I would like to do Not Working

#####collections/fritkots.js
search: (query) => {
if (Fritkots.find({}).count() > 0 ) {
return Fritkots.find({
name: { $regex: RegExp.escape(query), $options: ‘i’ }
}, {
limit: 3
});
} else {
throw new Meteor.Error(‘nothing-found’, ‘We were unable to do the query’);
}

search/search.js

Template.search.helpers({
searchResults: () => {
return Meteor.call(‘search’, Session.get(‘fritkotsSearchQuery’));


#2

Can you explain how it’s not working - are you seeing any error messages for example? Are you sure your Method is being registered properly? It looks like you’re omitting code above so it’s difficult to tell - is your search Method is being registered via a Meteor.methods call?


#3

Method calls on the client are asynchronous, so your return Meteor.call('search', Session.get('fritkotsSearchQuery')); in your helper is not returning the results but undefined

You need to do the following

Template.search.onCreated(function(){
 var self = this;
 self.searchResults = new ReactiveVar({});
}
Template.search.helpers({
 searchResults: () => {
  var self = Template.instance();
  Meteor.call('search', Session.get('fritkotsSearchQuery'), (err,res)=> {
   if(!err) self.searchResults.set(res);else console.error(err);
  });
  return self.searchResults.get();
 }
})