1
假设我有一个字段foo
的集合,我想获得唯一值的计数。流星和反应'不同'
Collection.distinct('foo').length;
我想在我的模板中有可用的值,如{{ fooCount }}
。
我该如何做到这一点,并且在流星中有这个数字?
假设我有一个字段foo
的集合,我想获得唯一值的计数。流星和反应'不同'
Collection.distinct('foo').length;
我想在我的模板中有可用的值,如{{ fooCount }}
。
我该如何做到这一点,并且在流星中有这个数字?
这将是这样的:
Template.yourTemplateName.helpers({
fooCount() {
var foos = CollectionName.find({foo: {$exists: true}})
.map(d => d.foo);
return _.uniq(foos).length;
}
});
这将是反应性的,因为它是使用反应性数据源的模板帮手。请注意,使用underscores是核心流星的一部分。
也只是为了好玩,你可以这样做:
Template.yourTemplateName.helpers({
fooCount() {
return CollectionName.find({foo: {$exists: true}})
.map(d => d.foo)
.reduce((acc, b) => _.contains(acc, b) ?
acc : acc.concat(b), []).length
}
});
这是只有当出版物发布整个集合。如果您只想在具有不同结果的字段查询中发布集合的游标,该怎么办?祝你好运。 – evolross
您是否遵循了已经发布的文档在扩展为例? (http://docs.meteor.com/#/full/meteor_publish)寻找“按房间计数”。 –
是的,上面加上一个包添加服务器端聚合与distinct()应该得到你想要的。这是广泛使用:https://atmospherejs.com/monbro/mongodb-mapreduce-aggregation –