我有两个收藏。一个称为帖子,另一个称为类别。在 posts 集合中,是各个帖子,每个帖子都包含一个名为 categories
的 id 数组,这些 id 是存储在帖子中的各个帖子所属类别的 id。
第二个集合是类别集合,其中包含每个帖子所属的类别
目标
在我的模板中,我将每个帖子显示为其标题、内容、图像和作者以及通过将帖子集合中的类别 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>
似乎不起作用。
进度
它不起作用,因为我没有为我的示例帖子分配类别,上面编辑的代码就是答案
最佳答案
我用于此类内容的另一个解决方案只是显示该帖子数组中的类别,甚至没有帮助程序。这就是我所做的...
方法内部:
//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 并在类别存在时增加计数的原因是针对多个不同的用例,例如:
在搜索中显示现有类别,以便始终返回现有文档
如果编辑/删除帖子,如果
count == 1
,如果count > 1
则删除该类别,减少该类别的计数。当用户添加/编辑帖子时显示现有类别的引用。根据他们在输入上写的内容,我使用正则表达式返回类别推荐。
在帖子中,仅显示帖子中的类别名称。无需查找类别。
<!--
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})
我看到您将其他内容保存到类别集合中,我可能会将其保存到帖子本身中,有些内容,如果它们像链接等,我什至不会在客户端保存和生成必要的内容。
关于javascript - 通过 ids 创建 2 个 mongodb 集合之间的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40581064/