Reputation: 63
Say I have a Meteor site where I want a function to search for a document in a collection and display it to the user.
This collection is very large and is not feasible to keep all on the client.
I have a publish statement that specifies what documents need to be pushed to the user.
Meteor.publish('listing', function (search) {
return TestObjs.find({"name": search });
});
And I have a search input textbox which when it changes I'd like to subscribe to the publication to get the records that I need.
'change #searchText' : function(e,t){
Session.set("searchTerm", $("#searchText").val());
Meteor.subscribe("listing", $("#searchText").val());
}
So every time I search for text, client is getting sent the documents it needs to be displayed.
The problem is, the subscribe call doesn't delete any old documents from the client for previous search terms. So the first problem is the more the user uses the search function, the more documents are going to be stored on the client. Secondly, if I want to display the search results for the current search term, I cannot just go
Template.home.helpers({
listOfObjs: function () {
return TestObjs.find().fetch();
}
});
This will return all record on the client which would be all records that match the current and any previous search term.
I have to replicate the publish statement
Template.home.helpers({
listOfObjs: function () {
return TestObjs.find({"name": Session.get("searchTerm") }).fetch();
}
});
This works, but I'm essentially duplicating the logic in multiple places. This is just a simple example but what if my search algorithm was more complicated with paging etc.
So I was wondering, what is the recommended Meteor way to return search results for collections that sit on the server?
Upvotes: 1
Views: 103
Reputation: 5023
Answer without try. Hope you looking for this.
var list;
'change #searchText' : function(e,t){
Session.set("searchTerm", $("#searchText").val());
if (list)
list.stop();
list = Meteor.subscribe("listing", $("#searchText").val());
}
From the doc
stop()
Cancel the subscription. This will typically result in the server directing the client to remove the subscription's data from the client's cache.
Upvotes: 1