title: Duplicate IDs in Local Collection when Meteor subscription changes
body: <p>Here's my scenario:</p>
  
  <p>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 <code>LocalEvents</code>. I loop through all of my events that are published from the <code>Events</code> collection, and insert a new document in to my local collection for each occurrence of my event.</p>
  
  <p>Here is my code with comments </p>
  
  <pre><code>//create reactive variable
  const searchQuery = new ReactiveVar(null);
  
  export default createContainer(({ params }) =&gt; {
      //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) =&gt; {
                  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);
  </code></pre>
  
  <p>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.</p>
  
  <p>How can I ensure the collection is properly emptied in my container every time the searchQuery changes?</p>
  
  <p>Thanks in advance</p>
  
  <p>** EDIT - FOUND SOLUTION **</p>
  
  <p>I added the solution I found as an answer</p>