流星-仅发布集合的计数
是否可以仅将集合的计数发布给用户?我想在首页上显示总数,但不希望将所有数据传递给用户.这是我尝试过的方法,但是不起作用:
Is it possible to publish just the count for a collection to the user? I want to display the total count on the homepage, but not pass all the data to the user. This is what I tried but it does not work:
Meteor.publish('task-count', function () {
return Tasks.find().count();
});
this.route('home', {
path: '/',
waitOn: function () {
return Meteor.subscribe('task-count');
}
});
尝试此操作时,我会得到无尽的加载动画.
When I try this I get an endless loading animation.
Meteor.publish
函数应该返回游标,但是在这里,您直接返回的是Number
,它是Tasks
集合中文档的总数.
Meteor.publish
functions should return cursors, but here you're returning directly a Number
which is the total count of documents in your Tasks
collection.
在Meteor中对文档进行计数比要以正确的方式完成任务要困难得多:使用既优雅又有效的解决方案.
Counting documents in Meteor is a surprisingly more difficult task than it appears if you want to do it the proper way : using a solution both elegant and effective.
包 ros:publish-counts (fastCount选项.
The package ros:publish-counts (a fork of tmeasday:publish-counts) provides accurate counts for small collections (100-1000) or "nearly accurate" counts for larger collections (tens of thousands) using the fastCount
option.
您可以通过这种方式使用它:
You can use it this way :
// server-side publish (small collection)
Meteor.publish("tasks-count",function(){
Counts.publish(this,"tasks-count",Tasks.find());
});
// server-side publish (large collection)
Meteor.publish("tasks-count",function(){
Counts.publish(this,"tasks-count",Tasks.find(), {fastCount: true});
});
// client-side use
Template.myTemplate.helpers({
tasksCount:function(){
return Counts.get("tasks-count");
}
});
您将获得客户端的响应计数以及服务器端的合理性能实现.
You'll get a client-side reactive count as well as a server-side reasonably performant implementation.
在(收费的)防弹流星课程中讨论了此问题,该课程建议阅读: https://bulletproofmeteor.com /
This problem is discussed in a (paid) bullet proof Meteor lesson which is a recommended reading : https://bulletproofmeteor.com/