Return objects 来自 mongo 在相似时间插入

Return objects from mongo inserted at similar time

我正在尝试将具有相似时间范围的用户插入到 collection 中的文档组合在一起。我正在寻找文档或代码片段来推动我在这个伪代码上朝着正确的方向前进;

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).

为清楚起见编辑:

带有时间戳的数据库发布功能正在运行,我可以在下面正确地看到存储在我的 collection 中的文档;

{ "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" } 

如何将在同一小时内提交的文档组合在一起(例如 'beef' 文档和 return 给用户的文档?我有一个基本的 return 函数 return 是所有条目,但我找不到太多关于按小时对数据进行分组的信息。

Meteor.publish('theFoods', function(){
    var currentUser = this.userId;

    return Foods.find({
        createdBy: currentUser
    })
});

您可以添加如下助手:

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();
  }
});

这将 return 一个 hourfoods 对的数组,如下所示:

[ { 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>