How to dynamically increment the limit on a collection cursor

I’m currently trying to implement a “Load more” button on a simple news page.

I’ve got the search working, thanks to Meteor Chef, and I followed the same principles to implement a “Load more” button. The relevant code is as follows:

Template:

Template.listAllNews.onCreated(function() {
  template.limit = new ReactiveVar(10);
  Tracker.autorun( () => {
    template.subscribe( 'news.all', template.searchQuery.get(), template.limit.get(), () => {
      setTimeout( () => {
        template.searching.set( false );
      }, 300 );
    });
  });


Template.listAllNews.events({
  'click .load-more-button': function (event, template) {
    var limit = template.limit.get();
    limit += 10;
    template.limit.set( limit );
  }
});

Publication:

let query      = {},
    projection = { limit: limit, sort: { submitted: -1 } };

if ( search ) {
  let regex = new RegExp( search, 'i' );
  query = {
    $or: [
      { title: regex }
    ]
  };
  projection.limit = 100;
}
return News.find( query, projection );

This works. The problem is: it refreshes all the data instead of just loading the extra 10 news articles. I want it to only load the extra 10 articles upon click, and not to “refresh” the subscription.

How can I do that?

So the way to do this may be to actually push the news elements to an array in your template, and then use mongo’s skip operator on your publication to skip the elements you’ve already retrieved. Every time you “Reset” your subscription, you push those new elements to your news element array, which you feed into your template for rendering.

https://docs.mongodb.org/manual/reference/method/cursor.skip/

Just to add - when you fetch 10 more news articles you aren’t fully “refreshing” the subscription. If you start with 10 articles then request the next 10 through your subscription/publication (so you’re retrieving 20 records from the database in your publication), all retrieved records are first fired over to your client connections “mergebox” (which is an on server cache). Only the records that aren’t already cached (in your case the newest 10 records) will then be sent back to the client. Check the Subscription lifecycle section of the Guide for a more in-depth explanation.