mongodb - 如何在 Meteor 中读取依赖于另一个集合的集合

标签 mongodb meteor

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

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}});

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

最佳实践是什么?谢谢!

最佳答案

服务器端代码:

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 查看整个示例。

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

关于mongodb - 如何在 Meteor 中读取依赖于另一个集合的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19913474/

相关文章:

mongodb - 如何返回数组字段大小大于给定数字的所有文档?

python - mongodb 查询中的逻辑运算符与 python

meteor :未捕获的 RangeError:超出最大调用堆栈大小

javascript - 在 Meteor 中,我如何识别服务器上站点的连接/用户,无论他们是否登录?

meteor - 如何将 "Google Tag Manager"与望远镜 meteor js 集成?

javascript - 如何在 Meteor 中使用 PureRenderMixin (React js)

php - 是否有 NoSQL 解决方案的比较(在某些情况下哪个更好?)

node.js - 没有数组且没有引用的嵌入文档

javascript - 从 Node 批量插入 mongoDB

javascript - 将 disqus 添加到 meteor.js 项目