Meteor app with live search responding extremely slow

Meteor app with live search responding extremely slow

When I ran my Meteor app with live search on my own server instead of locally the app was responding extremely slow. Chrome even showed a spinner when the app loaded. I needed to wait at least 20 seconds before I could even enter a query in the search field.

meteor-logo

The I read something which reminded me of the Meteor todo tutorial: you should remove the autopublish package which I completely forgotten.

Even tough I removed the autopublish package I still had a very slow app. So I started to digg into my code. This is what my extreme slow responding code looked like:

Items = new Mongo.Collection("items");

if (Meteor.isClient) {
  
  Meteor.subscribe("items", Session.get('search'));
  
  Template.main.helpers({

    items: function() {
      
      var search = Session.get('search');
      var re = new RegExp(search, 'i');
      
      return Items.find({
        name: re
      }, {
        limit: 25,
        sort: { price: 1}
      });
    }
  });
  
  
  Template.main.events({
    'keyup #q': function() {      
      return Session.set('search', $('#q').val());
    }
  });
    
}

if (Meteor.isServer) {
  
  Meteor.publish('items', function () {
    return Items.find({});
  });
  
}

A more experienced Meteor developer immediately sees what went wrong: The serverĀ  returned all the records and the client does the filtering of these records. My database contains about 800 prices so all of these were sent to the client.

I figured out how to do the filtering on the server side which made my app very smooth since only a maximum of 25 records needed to be transmitted. A StackOverflow article told me about to use the itemsHandler.stop(); in order to make livesearch work.

Items = new Mongo.Collection("items");
 
if (Meteor.isClient) {
 
  Meteor.subscribe("items", Session.get('search'));
 
  Template.main.helpers({
 
    items: function() {
 
      var search = Session.get('search');
      var re = new RegExp(search, 'i');
 
      return Items.find({});
 
    }
  });
 
  var itemsHandler = false;
 
  Template.main.events({
    'keyup #q': function() {      
 
      if (itemsHandler) {
        itemsHandler.stop();
      }
 
      itemsHandler = Meteor.subscribe("items", Session.get('search'));
 
      return Session.set('search', $('#q').val());
 
    }
  });
 
}
 
if (Meteor.isServer) {
 
  Meteor.publish('items', function (keyword) {
 
    var re = new RegExp(keyword, 'i');
 
    return Items.find({
      name: re
    }, {
      limit: 25,
      sort: { price: 1}
    });
 
  });
 
}

Leave a Reply

Your email address will not be published. Required fields are marked *