【问题标题】:Meteor Blaze template helper wait for collection find to "SELECT DISTINCT"Meteor Blaze 模板助手等待集合查找到“SELECT DISTINCT”
【发布时间】: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


【解决方案1】:

所有给定的代码都不需要 Mongo 的聚合函数,但可以通过正常的查询功能来解决:

if(!categories.includes(doc.category)) 可以使用$in 运算符求解,.sort() 可以使用sort 变换操作求解:

'jobs': function(){
  return Jobs.find({ category: { $in: categories } }, { sort: { category: 1 } })
},

返回值是Mongo.Cursor,它将触发更改的响应。

读数:

https://docs.mongodb.com/manual/tutorial/query-documents/

https://docs.meteor.com/api/collections.html#sortspecifiers

http://blazejs.org/api/templates.html#Template-helpers

【讨论】:

  • 这个解决方案需要一个填满的数组categories,它是空的,因此不起作用。我用一个例子更新了我的帖子,我只需要事先不知道“类别”字段的唯一值。
猜你喜欢
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 2016-04-30
  • 2014-05-12
  • 2015-01-06
  • 2015-09-26
  • 2015-09-20
  • 2017-11-16
相关资源
最近更新 更多