【问题标题】:How to read a collection that depends on another one in Meteor如何在 Meteor 中读取依赖于另一个集合的集合
【发布时间】:2013-11-11 18:41:50
【问题描述】:

我正在尝试从集合中加载最新帖子,同时加载同一帖子的所有 cmets。该集合具有引用,而不是将整个文档存储在彼此内部:

Post { title, body, etc..}
Comment { postId, body, etc.. }

我使用 iron-router 作为路由包,在我的页面路由中我是这样订阅的:

this.route('home', {
    path: '/',
    template: 'home',
    waitOn: function () {
        return [
            Meteor.subscribe('latestPost'),
            Meteor.subscribe('lastReadPost')
            ];
    }
});

检索帖子的代码很简单:

Posts.findOne({}, {sort:{createdAt:-1, limit:1}});

现在的问题是我不知道如何在不阅读整个集合的情况下检索 cmets。我无法在路由器中订阅,因为我仍然没有帖子 ID 来查询评论集合。 我猜我可以从模板中做到这一点,但当然,如果我查询评论集合,它仍然是空的。但我确实有 postId,因为它当时在 Posts 集合中。但我需要从模板触发订阅,这听起来不是一个干净的解决方案。

最佳做法是什么?谢谢!

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    服务器端代码:

    Meteor.publish("latestPost", function () {
      var post = Posts.find({}, {sort:{created:-1}}).fetch()[0];
      console.log("publish : " + post.title);
      return [
        Posts.find({_id: post._id}),
        Comments.find({postId: post._id})
      ];
    });
    

    客户端代码:

     this.route('home', {
        path: '/',
        template: 'home',
        waitOn: function () {
          return [
            Meteor.subscribe('latestPost')
          ];
        },
        data:function(){
          return {
           post:Posts.findOne(),
           comments:Comments.find()
          };
        }
       });
    

    查看此 repository 以查看整个示例。

    用户更改到另一条路线后,订阅将自动停止。

    【讨论】:

    • 这正是我所需要的。非常感谢!
    【解决方案2】:

    我还会在服务器端查找器选项中包含一个限制

    {排序:{创建:-1},限制:1}

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 1970-01-01
      • 2015-10-30
      • 2016-01-25
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2015-04-09
      • 2016-03-20
      相关资源
      最近更新 更多