Here's my scenario:
I have a collection of calendar events. Some events have a recurrence rule attached to them. When I subscribe to events in the client, I'm creating a new local collection called LocalEvents
. I loop through all of my events that are published from the Events
collection, and insert a new document in to my local collection for each occurrence of my event.
Here is my code with comments
//create reactive variable
const searchQuery = new ReactiveVar(null);
export default createContainer(({ params }) => {
//subscribe to subscription passing the reactive var as the variable
const subscription = Meteor.subscribe('Events.publications.admin.list.all', searchQuery.get());
const loading = !subscription.ready();
const allEvents = Events.find();
//loop through cursor, if event recurs - create new document for the event and insert it in to LocalEvents collection
allEvents.forEach(function(event) {
if (event.eventRecurs) {
//grab array of all recurring dates
const dates = event.recurringDates;
//loop through recurring dates and create new event document for each with a random ID and a parentId of the original event
_.each(dates, (date) => {
LocalEvents.insert({
'_id': Random.id(),
'name': event.name,
'description': event.description,
'defaultDate': date,
'parentId': event._id
});
})
} else {
//if event doesn't recur, set parentId and insert into local collection
event.parentId = event._id;
LocalEvents.insert(event);
}
});
const events = LocalEvents.find({}, { sort: { defaultDate: 1 }}).fetch();
//pass everything to the component
return { loading, events, searchQuery };
}, AdminEventsAll);
My problem is that when my subscription changes (by using a search bar) - it seems that the local collection still holds some documents in it as there are repeated instances of the events. The argument I pass to my subscription (searchQuery) is set each time a key is pressed in a search bar in my UI - this creates a reactive search. As I type, for each letter I type I see the documents duplicate. It basically shows that the local collection is refilling with the same documents so they are repeating over and over again.
How can I ensure the collection is properly emptied in my container every time the searchQuery changes?
Thanks in advance
** EDIT - FOUND SOLUTION **
I added the solution I found as an answer