Mongodb 使用mongo和meteor时出现两次类别
我正在Meteor的一个简单应用程序中做一个Todo应用程序 我在iClient部分中定义了一个集合及其助手函数Mongodb 使用mongo和meteor时出现两次类别,mongodb,meteor,Mongodb,Meteor,我正在Meteor的一个简单应用程序中做一个Todo应用程序 我在iClient部分中定义了一个集合及其助手函数 ToDo = new Meteor.Collection('todo'); if (Meteor.isClient) { Template.categoryList.helpers({ category: function(){ return ToDo.find({},{sort: {cat: 1}});; } }); Templ
ToDo = new Meteor.Collection('todo');
if (Meteor.isClient) {
Template.categoryList.helpers({
category: function(){
return ToDo.find({},{sort: {cat: 1}});;
}
});
Template.todo.helpers({
list: function(){
return ToDo.find();
}
我的模板文件如下所示
<template name="categoryList">
<div class="col-sm-3">
<ul class="list-group checked-list-box">
{{#each category}}
<li class="list-group-item">{{cat}}</li>
{{/each}}
</ul>
</div>
</template>
<template name="todo">
<div class="col-lg-6">
<ul class="list-group checked-list-box">
{{#each list}}
<!--<li class="list-group-item">{{tasks}}</li>-->
<div class="checkbox {{selectedClass}}">
<label>
<input class="{{selectedClass}}" type="checkbox" value=""> {{tasks}}
</label>
</div>
{{/each}}
</ul>
</div>
</template>
请给我一些见解
谢谢您返回的文档来自同一个集合,因此列表中有三个“项目”,因此列出了三个“类别”。您列出的是列表中每个“项目”的等效类别,而不是唯一类别的列表
Template.categoryList.helpers({
category: function(){
return ToDo.find({},{sort: {cat: 1}}); // This is the ToDo collection
}
});
Template.todo.helpers({
list: function(){
return ToDo.find(); // This is also the same ToDo collection
}
您将从同一集合返回完全相同的文档,只是对它们进行不同的排序,并从同一文档输出不同的字段
您需要找到“不同的”值:
因此,只需根据上述参考将您的类别帮助器更改为:
Template.categoryList.helpers({
category: function(){
var distinctCategories = _.uniq(ToDo.find({}, {
sort: {cat: 1}, fields: {cat: true}
}).fetch().map(function(doc) {
return doc.cat;
}), true);
return distinctCategories;
}
});
或者您需要将类别存储在它们自己的集合中,然后从todo项中分别引用它们,通常是通过引用_id
更新:我们可以删除fetch调用并执行以下操作:
Template.categoryList.helpers({
category: function(){
var distinctCategories = _.uniq(ToDo.find({}, {
sort: {cat: 1}, fields: {cat: true}
}).map( function(doc) {return doc.cat;
}), true);
return distinctCategories;
}
});
迭代器不会显示数据,因为.map函数返回一个数组,所以我们可以在类别模板中执行以下操作:
<template name="categoryList">
<div class="col-sm-3">
<ul class="list-group checked-list-box">
{{#each category }}
<li class="list-group-item">{{this}}</li>
{{/each}}
</ul>
</div>
</template>
我真的对mongo db的东西感到困惑,你能不能抛出一些代码来更详细地解释它。PlzI认为为category和items创建两个集合表是错误的。我的印象是,这是sql方式,我在mongo网站上看到过类似的复杂模式。是的,你是对的。规范化模式是典型的SQL,但您仍然可以将其用于NoSQL。一般的做法是根据数据最频繁的使用情况来组织数据,通常是从中读取数据,而不是向中写入数据。所以非规范化对于您的案例来说是有意义的,就像您选择的那样。我只是提供了一个可选的.collection.distinct返回类型错误,所以我想它在meteor中还不受支持。所以我必须找到其他方法来做这件事是的,它还不被支持。阅读我发布的链接,并查看我的更新答案。
<template name="categoryList">
<div class="col-sm-3">
<ul class="list-group checked-list-box">
{{#each category }}
<li class="list-group-item">{{this}}</li>
{{/each}}
</ul>
</div>
</template>