Mongodb 分组和显示数据
这是我的数据Mongodb 分组和显示数据,mongodb,meteor,Mongodb,Meteor,这是我的数据 data = [ { category : "Cat1"}, { category : "Cat2"}, { category : "Cat3"}, { category : "Cat4"}, { category : "Cat5"}, { category : "Cat6"}] 假设我把它放在一个名为myData的集合中 我想要的是将我的数据分组并显示在2组中。 然后我在导航栏中显示它(事实上是在下拉列表中),如下所示 <ul> {
data = [
{ category : "Cat1"},
{ category : "Cat2"},
{ category : "Cat3"},
{ category : "Cat4"},
{ category : "Cat5"},
{ category : "Cat6"}]
假设我把它放在一个名为myData的集合中
我想要的是将我的数据分组并显示在2组中。
然后我在导航栏中显示它(事实上是在下拉列表中),如下所示
<ul>
{{#each group}}
<li class="col-md-2">
<ul>
{{#each categories}}
<li>{{category}}</li>
{{/each}}
</ul>
{{/each}}
<ul>
{{{每组}
-
{{{#每个类别}
- {{category}}
{{/每个}}
{{/每个}}
我要问的是如何在我的助手或mongodb中对数据进行分组,以便得到这个结果 我不是100%清楚您所说的“组”是什么意思,但假设您使用的是Boostrap导航栏下拉列表,您可以使用分隔符将其分组:
{{#each categories}}
<li>{{category}}</li>
{{#if doSeparator @index}}
<li role="separator" class="divider"></li>
{{/if}
{{/each}}
另一方面,如果您希望每个组都有子菜单,则需要将数组分为两个级别。您可以使用下划线的
映射和压缩将其在辅助对象中分成两组
Template.hello.helpers({
groups() {
// var data = myData.find().fetch();
var data = [
{ category : "Cat1"},
{ category : "Cat2"},
{ category : "Cat3"},
{ category : "Cat4"},
{ category : "Cat5"},
{ category : "Cat6"}];
return _.chain(data).map(function(item, index){
return (index % 2) ? false : data.slice(index, index + 2);
}).compact().value();
},
});
然后,在模板中,您可以使用嵌套的#each in
在组中循环
<template name="hello">
<ul>
{{#each group in groups}}
<li class="col-md-2">
<ul>
{{#each category in group}}
<li>{{category.category}}</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
</template>
{{#每个组中的每个组}
-
{{#组中的每个类别}
- {{category.category}
{{/每个}}
{{/每个}}
另一种方法可以是:
<ul>
{{#each groups}}
<li>
<ul>
{{#each this}}
<li>{{category}}</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
这将使用lodash的函数将返回的数组拆分为两个项目的分组(因此,如果尚未安装meteor npm,则需要save lodash)
以上内容将为您提供如下输出:
<ul>
<li>
<ul>
<li>1</li>
<li>2</li>
</ul>
</li>
<li>
<ul>
<li>3</li>
<li>4</li>
</ul>
</li>
<li>
<ul>
<li>5</li>
<li>6</li>
</ul>
</li>
</ul>
-
- 1
- 2
-
- 3
- 4
-
- 5
- 6
所以每个组至少有2个类别,这就是我的要求是的,我使用引导导航栏下拉列表,但我想知道我应该在助手中放置什么来将类别2按2分组。你的剂量计已经分组了吗?“分组”可以是很多东西。根据我答案中的代码,您将在每两项后获得一个分隔符。(索引%2)是索引模数2,当索引为1、3、5等时为真。因此,菜单中的项目将直观地分为2和2。或者您想在菜单中的每一行添加项目,这就是您所说的“组”吗?是的,它是在帮助器处对数组进行分组。回答得好!这超出了我的知识范围,但我将尝试这样做,并尝试了解它是否适用于Meteor附带的JS库-请参阅(在页面上搜索链
、映射
和压缩
方法)<代码>#
中的每一个都在这里
import { Template } from 'meteor/templating';
import chunk from 'lodash/chunk';
import { myData } from '/imports/api/mydata/collection';
import './main.html';
Template.someTemplate.helpers({
groups() {
return chunk(myData.find().fetch(), 2);
},
});
<ul>
<li>
<ul>
<li>1</li>
<li>2</li>
</ul>
</li>
<li>
<ul>
<li>3</li>
<li>4</li>
</ul>
</li>
<li>
<ul>
<li>5</li>
<li>6</li>
</ul>
</li>
</ul>