排序和限制不适用于Mongo + Meteor [英] Sort and limit not working with Mongo + Meteor
问题描述
这是我发布收藏集的publish.js
文件:
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:
-
排序和限制不起作用:我有时会得到3个以上的结果,并且没有按计数"进行排序
sort and limit are not working: I sometimes get more than 3 results and there are not sorted by 'counts'
回调无法正常工作.太快了,我在客户端和服务器上得到了不同的结果.我尝试使用onSuccess()
和Meteor.autorun()
这样,但是没有运气.如果使用setTimeout
,我可以看到正确的光标
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.
推荐答案
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
.
第二,查看您的代码,我假设您的出版物期望至少一个参数:searchString
.但是您订阅的代码不会通过.我认为应该是这样的:
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.
例如,假设您找到的查询为{ num: { $gte: 1 } }
,并且有3个满足此条件的文档,num
s分别等于3
,2
和1
.这3个文档将从该出版物发送到客户集合.
For example, let's assume that you have find query as { num: { $gte: 1 } }
and there are 3 documents which satisfy this condition, with num
s equal 3
, 2
and 1
accordingly. These 3 documents will be sent to client collection from this publication.
现在,让我们使用num: 2.5
将新文档添加到此mongo集合中.考虑到您将{ limit: 3 }
作为查询选项,将会发生什么情况?该出版物将发送给客户端:removed
事件(对于带有num: 1
的文档)和added
事件(对于带有num: 2.5
的文档).客户端集合将按该顺序具有文档:3, 2, 2.5
.
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();
另外,请参阅有关何时发生的文档发布参数已更改.
这篇关于排序和限制不适用于Mongo + Meteor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!