在Meteor上,从循环中获取另一个集合中的数据

时间:2015-04-19 00:47:38

标签: node.js meteor

我有一个集合,用于存储用户关注的帖子列表,每个用户都有自己的文档。它的结构如下:

{"_id": "12365",
"user": "123548" //user ID
"posts" : [
   {"postId": "225"},
   {"postId": "688"},
   {"postId": "55"},
   (...)
]}

user键是指使用_id包创建的该用户的account

我想在用户个人资料页面上列出用户关注的所有帖子,但我无法通过每个postId显示postTitle而不是其ID。

呈现列表的HTML是这样的:

<p class="title"><a href="#">{{postId}}</a></p>

获取该用户关注帖子的模板助手是这样的:

Template.singleUser.helpers({
    postsLibrary: function () {
        var postsLibraryContent = postsLibrary.find({
            user: Meteor.user();
        });
    },
});

如何从跟踪帖子的集合中循环访问posts数组,但是显示引用每个title的每个帖子postId?我应该在上面这个助手里面做什么吗?

- 更新 -

标题存储在帖子集合中,如下所示:

{
    "_id": "9845", //same as postId from the other collection
    "title": "Lorem Ipsum",
    "author": "Peter Parker",
    (...)
} 

2 个答案:

答案 0 :(得分:0)

从此

更改您的HTML

<p class="title"><a href="#">{{postId}}</a></p>

到此

{{#each posts}}
    <p class="title"><a href="#">{{postId}}</a></p>
{{/each}}

这会遍历数组帖子。

答案 1 :(得分:0)

好的,明白了!

Template.singleUser.helpers({
  postsLibrary: function () {
    var data = [];

    //first we find all this current user postLibrary collection
    var postsLibraryContent =  PostsLibrary.find({
        user: this._id
    }).posts;

    //then for each item on `posts` array:
    for (var i = 0; i < postsLibraryContent.length; i++) {

        //get that array item postId value and store on a var
        var postId = postsLibraryContent[i].postId;

        //creates an array with the post data by searching for its _id
        postData = Posts.find({
            _id: postId
        }).fetch();            

        //and then push those data to an array above created
        data.push({
            postTitle: postData[0].title,
            postAuthor: postData[0].author
        })

    };

    //then return data array
    return data;

  }
});

并在HTML上呈现:

{{#each postsLibrary}}
     <li>
         <p class="title"><a href="">{{postTitle}} - {{postAuthor}}</a></p>
     </li>
{{/each}}