为什么即使我已经订阅了该集合(Meteor),文档仍返回 null

Why is the document returning null even though I already subscribed to the collection (Meteor)?

本文关键字:Meteor 文档 null 返回 集合 为什么      更新时间:2023-09-26

我有一个BooksChapters集合。不言自明:一本书可以有很多章节。

订阅.js:

Meteor.publish("singleChapter", function(id) {
  return Chapters.find(id);
});

book_page.js:

Template.bookPage.helpers({
  chapters: function() {
    Chapters.find({
      bookId: this._id
    }, {
      sort: {
        position: 1
      }
    });
  }
});

book_page.html:

<template name="bookPage">
  <div class="chapter-list hidden">
    <div class="chapter-items">
    {{#each chapters}}
      {{> chapterItem}}
    {{/each}}
    </div>
  </div>
</template>

chapter_item.html:

<template name="chapterItem">
  <div class="chapter clearfix">
    <div class="chapter-arrows">
      <a class="delete-current-chapter" href="javascript:;">X</a>
    </div>
  </div>
</template>

现在,我正在尝试获取chapter_item.js中的当前章节项目:

Meteor.subscribe("singleChapter", this._id); // even tried this but didn't work
Template.chapterItem.events({
  "click .delete-current-chapter": function(e) {
    e.preventDefault();
    var currentChapter = Chapters.find(this._id);
  }
});

但是当我这样做时

console.log(currentChapter);

我得到undefined.我做错了什么?

TL/DR - 跳到 3,因为它可能是最相关的,但为了完整起见,我已经包括了其余部分。

  1. 我假设您将console.log...行放在"click .delete-current-chapter"回调中? currentChapter变量将是该函数的本地变量,因此通过在控制台中输入该变量不会获得任何内容。 如果这是显而易见的,请道歉,但不清楚你是否从这个问题中这样做。

  2. 即使在回调中,currentChapter也将是一个光标,而不是一个文档或文档数组。 使用 findOne 返回单个文档(或 null(,或使用 find(query).fetch() 返回数组(在这种情况下可能只是一个文档(。

  3. 您尝试在何时何地订阅singleChapter? 如果它在回调中,你必须记住这不是一个反应式函数。 这意味着您将订阅(一旦您知道要订阅的_id(,但在集合实际准备就绪之前立即返回currentChapter(因此其中没有任何内容(。 在这种情况下,集合准备就绪后,回调不会重新运行,因为事件处理程序不是反应性的。

    解决此问题的最简单方法是在订阅时使用onReady回调,并在其中设置currentChapter。 另一种方法是事件处理程序中的自动停止Tracker.autorun,但这似乎有点矫枉过正。

  4. 最后一点,您需要对具有这种设置的订阅更加小心,因为您可以轻松地为每个客户端累积数十个订阅,而不会停止Iron Router提供的自动订阅。 鉴于此用例,最好在运行回调并删除相关项目后立即停止订阅。

您的发布函数是否正常工作?也许 Mongo 有一个我不知道的功能,但我希望你需要包含{_id:id},而不仅仅是 (id(。

Meteor.publish('singleChapter', function(id){ return Chapters.find({_id: id}); });