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