Meteor publication sorting

316 views Asked by At

I have a Meteor-react app, what contains a collection, with a lots of data. I am displaying the data with pagination.
At the server side I am just publishing the data for the current page.

So, I am publishing some data at the server side:

Meteor.publish('animals', function(currPage,displayPerPage, options) {
  const userId = this.userId;
  if (userId) {
    const currentUser = Meteor.users.findOne({ _id: userId });
    let skip = (currPage - 1) * displayPerPage;
    if (displayPerPage > 0) {
      Counts.publish(this, 'count-animals', Animals.find(
        {$and: [
          // Counter Query
        }
      ), {fastCount: true});

  return Animals.find(
     {$and: [
       // Data query
     ]}, {sort: options.sortOption, skip: skip, limit: displayPerPage });
     } else {
       Counts.publish(this, 'count-animals', 0);
       return [];
     }
  }
});


And on the client side I am using tracker:

export default AnimalsContainer = withTracker(({subscriptionName, subscriptionFun, options, counterName}) => {
  let displayPerPage = Session.get("displayPerPage");
  let currPage = Session.get("currPage");
  let paginationSub = Meteor.subscribe(subscriptionName, currPage, displayPerPage, options );
  let countAnimals = Counts.get(counterName);
  let data = Animals.find({}).fetch({});
  // console.log(data);
  return {
    // data: data,
    data: data.length <= displayPerPage ? data : data.slice(0, displayPerPage),
    countAnimals: countAnimals,
  }
})(Animals);


The problem is:

When I try to modify the sort options on the client side, the server sort not from the first data(Skippind the first some). Sometimes from the 20 th sometimes from the 10 th. The type checks are done at both side.

1

There are 1 answers

3
Casey Gibson On

Two things I can think of.

  1. Keep on eye on the {sort: options.sortOption, skip: skip, limit: displayPerPage } order. As far as I know, it runs in the order you place it. So it sorts first, then skips, then limits.

  2. Do sorts on both client and server. When the sort happens on the server and it's streamed to the client, the client holds a mini mongo version which doesn't guarantee an order. Therefore you need to sort the client as well.