【发布时间】:2021-05-15 10:09:00
【问题描述】:
此 Meteor 客户端代码需要按字段“类别”对 mongo 集合中的文档进行分组,并返回字段“类别”的唯一值的排序数组。我正在使用 Blaze 模板助手,它返回一个由 collection.find.foreach 填充的数组,因为我找不到简单易懂的示例来说明如何聚合客户端的 mongo 集合,如何让助手等待集合操作准备好?谢谢
'jobs': function(){
let categories = []
Jobs.find({}).forEach((doc) => {
if(!categories.includes(doc.category)) categories.push(doc.category)
})
return categories.sort()
}
更新:添加示例
collection Jobs 有如下数据:
{'category':'Inspection','label':'Pink','discription':'R...}
{'category':'Inspection','label':'Blue','discription':'U...}
{'category':'Inspection','label':'AOR', 'discription':'A...}
{'category':'Inspection','label':'Prep','discription':'P...}
{'category':'Inspection','label':'Chec','discription':'I...}
{'category':'Inspection','label':'Diag','discription':'D...}
{'category':'Service','label':'basic','discription':'Cha...}
{'category':'Service','label':'regular','discription':'C...}
我需要字段类别的唯一值,即 (Inspection, Service)。
更新 2
在 mongo shell 上,解决方案是:
db.jobs.distinct( "category" ) 产生 ["Inspection","Service"]
【问题讨论】:
-
看来您要的是
How can I get the helper to wait till the collection operation is ready?。您能解释一下为什么这是您要解决的/一个问题,或者它的行为不符合您的意愿吗? -
return categories.sort()返回未定义。 -
不,它没有。至少不会,除非您在其他地方(未显示)添加了与
Array.prototype.sort的实现相混淆的代码。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Return value: The sorted array.不会返回undefined。 -
是的。你是对的。问题已解决。谢谢
标签: javascript meteor