Meteor - 返回集合 1 中的所有文档,然后查询集合 2 作为循环遍历集合 1

Meteor - return all documents from collection 1 and then query collection 2 as looping through collection 1

本文关键字:集合 查询 然后 遍历 循环 返回 Meteor 文档      更新时间:2023-09-26

我对Meteor(和Web编程)非常陌生,并设置了两个集合,一个称为Posts,另一个称为作者(我确实意识到我可以将所有这些信息放在一个集合中,但我想尝试这种方式)。我正在尝试显示所有帖子,所以我在 HTML 代码中执行每个帖子,这将遍历我的所有帖子。当我循环浏览我的帖子时,我正在尝试将帖子 ID 保存在隐藏输入中,以便我可以为每个帖子使用该 ID 来查询作者集合并显示作者姓名。我添加了一个控制台.log它每次都为我的 postId 写入未定义 - 知道为什么要这样做或解决此问题的更好方法(无需在帖子中嵌入作者信息)?

.html:

<template name="dashboard">
  {{#each eachPost}}
    <input type="hidden" id="postId" value="{{_id}}">
    <p>{{authorName}}</p>
  {{/each}}
</template>

.js:

Template.dashboard.helpers({
 eachPost: function()
 {
   return Posts.find({});
 },
 authorName: function()
 {
   var postId = $('#postId').val();
   console.log(postId);
   return Authors.findOne({_id: postId});
 }
});

提前感谢,我非常感谢任何和所有的帮助!

我认为没有必要将其存储在隐藏元素中

您可以使用authorname帮助程序中的this._id访问它

你可以像下面这样做

<template name="dashboard">
  {{#each eachPost}}
    <p>{{authorName}}</p>
  {{/each}}
</template>
Template.dashboard.helpers({
 eachPost: function()
 {
   return Posts.find({});
 },
 authorName: function()
 {
   console.log(this._id);
   return Authors.findOne({_id: this._id});
 }
});

试试这个,它可能对你有用