我正在使用:Meteor,JS和mongoDB。
我们说我有这样的文件:
document {
field 'a' : date(01/03/2016),
field 'b' : date(13/45/2015),
field 'c' : date(23/01/1987),
field 'd' : date(17/09/2000),
field 'e' : "hello"
}
我想'排序'在模板中(使用空格键的html):
23/01/1987 - the name I give to 'c'
17/09/2000 - Another name I give to 'd'
13/45/2015 - name of 'b'
01/03/2016 - name of 'a'
我真的不知道该怎么做。
我 - 当然 - 能够按照约会排序'但是如何检索'字段名称' (在正确的日期之前)?
我听说过'关联数组' ... 有什么线索吗?
答案 0 :(得分:0)
Blaze中没有默认功能。因此,您应该使用自定义帮助程序,如:
const fieldCaptionMap = {
a: 'My field a',
b: 'Field b',
c: 'Anouther field c'
};
Template.myTemplate.helpers({
yourDocument() {
return {
a: new Date('2016-01-02'),
b: new Date('2016-02-03'),
c: new Date('2016-03-04')
}
},
sortDocumentDates(doc) {
return Object.keys(doc)
.filter(key => _.isDate(doc[key]))
.map(dateKey => {
return {
field: dateKey,
date: doc[dateKey],
caption: fieldCaptionMap[dateKey]
};
})
.sort((entryA, entryB)=> {
return entryA.date.getTime() - entryB.date.getTime();
});
}
});
然后您的模板将如下所示:
<template name="myTemplate">
<ul>
{{#each sortDocumentDates yourDocument}}
<li>{{date}} - {{caption}}</li>
{{/each}}
</ul>
</template>
我不确定为什么你需要这样的结构,但是如果你要在你的文档中保留某种历史记录,那么更容易维护结构就像:
const myDocument = {
history: [
{
date: new Date('2016-01-02'),
action: 'documentCreate'
},
{
date: new Date('2016-01-03'),
action: 'documentUpdate'
},
{
date: new Date('2016-01-03'),
action: 'documentArchive'
}
]
//other document fields ...
};