通过ID

时间:2016-11-14 02:23:43

标签: javascript mongodb meteor mongo-collection

我有两个系列。一个称为帖子,另一个称为类别。在帖子集合中,每个帖子都包含一组名为categories的ID,这些ID是个人帖子所属类别中存储在帖子中的ID。

enter image description here

第二个集合是类别集合,其中包含每个帖子所属的类别

enter image description here

目标

在我的模板中,我将每个帖子显示为其标题,内容,图像和作者以及通过将帖子集合中的类别ID链接到类别集合中的各个类别而产生的类别名称

<template name="latest">
    {{#each posts}}
<div>{{> category}}</div>
      <h5 class="latest-title">{{title.rendered}}</h5>
  <img class="latest-img" src="{{featured_image_thumbnail_url}}" alt="" />
    {{/each}}
</template>

在我的类别模板

<template name="category">
  {{#each categories}}
 {{name}}
  {{/each}}

</template>

在我的category.js

Template.category.helpers({
  categories(){
    return CategoryCollection.find({ id: parseInt(this.categories) });
  }
});

正如您所看到的,我想显示属于帖子的类别的名称,它们是一个数组,因为帖子可能也有3个类别。但我似乎无法让它发挥作用。

修改

这是我的编辑,包括$in

Template.category.helpers({
  categories(){
    return CategoryCollection.find({ id: {$in: this.categories }});
  }
});

这是我的模板

<template name="category">
  {{#each categories}}
  {{name}}
  {{/each}}

</template>

它似乎无法正常工作。

的进展

它没有工作,因为我没有为我的示例帖子分配类别,上面编辑的代码就是答案

2 个答案:

答案 0 :(得分:1)

我正在使用的另一种解决方案就是显示该帖子的数组中的类别,甚至没有助手。这就是我做的......

方法内部:

//the categories is what you pass from the client as an array of strings
//IE: ['cat1', 'cat2']

categories.forEach(function(cc){
    const cat = Categories.findOne({name: cc});
    if(!cat){
        Categories.insert({
            name: cc,
            count: 1
        });
    } else {
        //increment count if it exists
        Categories.update({name: cc}, {
            $inc:{
                count: 1
            }
        });
    }
});

我插入计数1并在类别存在时递增计数的原因是针对多种不同的用例,例如:

  1. 在搜索中显示现有类别,以便始终返回现有文档

  2. 如果是编辑/删除帖子,如果是count == 1,请删除count > 1类别,减少该类别的计数。

  3. 在用户添加/编辑帖子时显示现有类别的引用。根据他们在输入上写的内容,我返回带有正则表达式的类别推荐。

  4. 在帖子中,只显示帖子中的类别名称。无需找到类别。

    <!-- 
        see that its {{this}} not {{name}} because 
        we saved the categories to the post as an array of strings 
        we'd do {{name}} if we were looping through the categories collection
    -->
    {{#each categories}}
        {{this}}
    {{/each}}
    

    如果您需要通过帖子中的数据库访问类别,例如点击活动,您可以快速Categories.findOne({name: this.name})

    我看到你将其他东西保存到Category集合中,我可能会保存到帖子本身和一些,如果它们像链接等,我甚至不会保存并生成必要的客户端。

答案 1 :(得分:0)

您想使用$in运算符:

 return CategoryCollection.find({ id: {$in: this.categories }});
相关问题