Sort and limit not working with Mongo + Meteor

心已入冬 提交于 2019-12-11 16:11:32

问题


This is my publish.js file in which I publish my collection:

const tags = Tags.find({title: {
      $regex: `.*${searchString}.*`,
      $options: 'i'
    }}, {
      sort: { counts: -1 }, limit: 3
    });
    console.log(tags.count());

    return tags;

And this is my components which is subscribing to this collection:

this.tagsSubscription = this.subscribe('tags', () => [this.tag], function (err) {
    that.tags = Tags.find().fetch();
});

So with this I get 2 different errors:

  • sort and limit are not working: I sometimes get more than 3 results and there are not sorted by 'counts'

  • the callback is not working properly. It's too fast, I get different result on client and server. I tried with this way, onSuccess() and with Meteor.autorun() but with no luck. If I use a setTimeout I can see the correct cursor

The title search is the only thing that seems working.


回答1:


First, according to documentation, .count() will ignore effects of .skip() and .limit(), so, for example, if you have 100 records in total, and your query options has { limit: 3 } then .count() for this cursor will return 100 instead of 3.

Second, looking at your code I assume that your publication expects at least one argument: searchString. But your code that subscribes to it doesn't pass it. I think it should be like that:

Meteor.subscribe('tags', this.tag, () => {
  that.tags = Tags.find().fetch();
});

And lastly, server-side sorting does not affect documents sorting in client-side collections.

For example, let's assume that you have find query as { num: { $gte: 1 } } and there are 3 documents which satisfy this condition, with nums equal 3, 2 and 1 accordingly. These 3 documents will be sent to client collection from this publication.

Now, let's add new document to this mongo collection, with num: 2.5. What will happen, considering you have { limit: 3 } as query options? The publication will send to client: removed event for document with num: 1 and added event for document with num: 2.5. And client-side collection will have documents in that order: 3, 2, 2.5.

Following this, it should be understandable that you should sort your documents on client side as well. So, in my code above it should be:

that.tags = Tags.find({}, { sort: { counts: -1 } }).fetch();

Also, have a look at documentation regarding what happens when publication arguments are changed.



来源:https://stackoverflow.com/questions/45957640/sort-and-limit-not-working-with-mongo-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!