我试图将具有相似时间范围的用户插入到集合中的文档组合在一起。我正在寻找文档或代码片段,以便在这个伪代码上向我推进正确的方向;
User submits a number of documents (over the course of five minutes) into a collection.
Documents are grouped together with similar timeframe.
User is returned a list of objects that were inserted within a timeframe (eg. 1hr).
为清晰起见编辑:
带有时间戳的数据库的发布功能正常,我可以在下面正确地看到存储在我的集合中的文档;
{ "text" : "beef", "createdBy" : "X9Px6qKRjiB53ANST", "createdAt" : ISODate("2015-02-03T00:47:21.976Z"), "_id" : "sJhwcLCRS4CG6yfTe" }
{ "text" : "beef", "createdBy" : "X9Px6qKRjiB53ANST", "createdAt" : ISODate("2015-02-03T00:47:41.265Z"), "_id" : "NGBwiWZRsDBbNerSy" }
{ "text" : "Chicken", "createdBy" : "X9Px6qKRjiB53ANST", "createdAt" : ISODate("2015-02-03T02:47:21.163Z"), "_id" : "R2FYAjZamTWTy9RTW" }
{ "text" : "Chicken", "createdBy" : "X9Px6qKRjiB53ANST", "createdAt" : ISODate("2015-02-03T04:42:02.895Z"), "_id" : "F7u2EfBEmYLBaFgze" }
如何将同一小时内提交的文件组合在一起(例如,牛肉文件并将其返回给用户?我有一个基本的返回功能,可以返回所有条目,但我可以'找到很多关于按小时分组数据的信息。
Meteor.publish('theFoods', function(){
var currentUser = this.userId;
return Foods.find({
createdBy: currentUser
})
});
答案 0 :(得分:1)
你可以添加一个帮手,如:
Template.myTemplate.helpers({
foodsByHour: function() {
var foods = Foods.find().fetch();
return _.chain(foods)
.groupBy(function(food) {
if (food.createdAt)
return food.createdAt.getHours();
})
.map(function(v, k) {return {hour: k, foods: v};})
.value();
}
});
这将返回hour
和foods
对的数组,如下所示:
[ { hour: '16',
foods:
[ { text: 'beef',
createdBy: 'X9Px6qKRjiB53ANST',
createdAt: Mon Feb 02 2015 16:47:21 GMT-0800 (PST),
_id: 'sJhwcLCRS4CG6yfTe' },
{ text: 'beef',
createdBy: 'X9Px6qKRjiB53ANST',
createdAt: Mon Feb 02 2015 16:47:41 GMT-0800 (PST),
_id: 'NGBwiWZRsDBbNerSy' } ] },
{ hour: '18',
foods:
[ { text: 'Chicken',
createdBy: 'X9Px6qKRjiB53ANST',
createdAt: Mon Feb 02 2015 18:47:21 GMT-0800 (PST),
_id: 'R2FYAjZamTWTy9RTW' } ] },
{ hour: '20',
foods:
[ { text: 'Chicken',
createdBy: 'X9Px6qKRjiB53ANST',
createdAt: Mon Feb 02 2015 20:42:02 GMT-0800 (PST),
_id: 'F7u2EfBEmYLBaFgze' } ] } ]
这是一个示例模板:
<template name='myTemplate'>
{{#each foodsByHour}}
<h2>{{hour}}</h2>
{{#each foods}}
<p>{{text}}</p>
{{/each}}
{{/each}}
</template>