流星:插入后集合为空

时间:2015-04-25 13:39:43

标签: meteor

我是流星的新手并且被困住了,无法理解我做错了什么。请赐教。

这是HTML文件:

<body>

  <h1>Do</h1>
  {{#if activeTask}}
    {{> currentTask}}
  {{else}}
    {{> newTask }}
  {{/if}}

  <div>

  </div>

</body>


<template name="newTask">
  <form>
    <label>What<input type="text" name="what" placeholder="gimme an action"/></label>
    <input type="submit" value="Go"/>
  </form>

  <!--
  {{> inputAutocomplete settings=settings id="msg" class="input-xlarge" placeholder="action"}}
  -->

</template>

<template name="currentTask">
  <form>
    <label>What<input type="text" name="what" placeholder="gimme an action"/>{{activeTask.what}}</label>
    <div>4h 15m</div>
    <input type="submit" value="Stop"/>
  </form>
</template>

这是JavaScript文件:

tasks = new Mongo.Collection('tasks');

if (Meteor.isClient) {

  Template.body.helpers({

    activeTask: function() {
      var task = tasks.findOne(
        {
          endAt: null
        },
        {
          sort: {
            startAt: -1
          }
        }
      );
      console.log(task);
      return task;
    }

  });

  Template.newTask.events({
    'submit' : function(event) {
      event.preventDefault();
      var now = Date.now();
      var what = event.target.what.value;
      tasks.insert({ what: what, startAt: now, endAt: null });
    }
  });

}

它成功地将新文档添加到数据库中,并将其记录在帮助程序activeTask中。一步之后,它根本不记录任务。它已经消失了。但为什么呢?

1 个答案:

答案 0 :(得分:2)

如果您没有安装软件包autopublishhttps://atmospherejs.com/meteor/autopublish),则需要创建发布(客户端)和订阅(服务器端):

if (Meteor.isServer) {
  Meteor.publish('tasks', function () {
    return tasks.find();
  });
}

if (Meteor.isClient) {
  Meteor.subscribe('tasks');
}

我在最近的博客文章中也解释过working with collections

相关问题