如何在 Meteor 中读取依赖于另一个集合的集合 [英] How to read a collection that depends on another one in Meteor
问题描述
我正在尝试从一个集合中加载最新的帖子,同时加载该帖子的所有评论.该集合具有引用而不是将整个文档存储在彼此内部:
I'm trying to load the latest post from a collection and at the same time all of the comments of that same post. The collection have references instead of storing the whole documents inside each other:
Post { title, body, etc..}
Comment { postId, body, etc.. }
我使用 Iron-router 作为路由包,并且在我的页面的路由中我以这种方式订阅:
I'm using iron-router as the routing package and in the route of my page I'm subscribing with this way:
this.route('home', {
path: '/',
template: 'home',
waitOn: function () {
return [
Meteor.subscribe('latestPost'),
Meteor.subscribe('lastReadPost')
];
}
});
检索帖子的代码很简单:
The code that retrieves the post is simply:
Posts.findOne({}, {sort:{createdAt:-1, limit:1}});
现在的问题是我不知道如何在不阅读整个集合的情况下检索评论.我无法在路由器中订阅,因为我仍然没有帖子 ID 来查询 Comments 集合.我猜我可以从模板中做到这一点,但是当然,如果我查询 Comments 集合,它仍然是空的.但我确实有 postId,因为它当时在 Posts 集合中.但我需要从模板触发订阅,这听起来不是一个干净的解决方案.
Now the problem is that I don't know how to retrieve the comments without reading the whole collection. I can't subscribe in the router as I still do not have the post ID to query the Comments collection. I guessed I could do that from the Template, but of course if I query the Comments collection, it's still empty. But I do have the postId as it's inside the Posts collection at that time. But I would need to trigger a subscription from the Template and that doesn't sound like a clean solution.
最佳实践是什么?谢谢!
What would the best practice be? Thanks!
推荐答案
服务器端代码:
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()
};
}
});
检查这个存储库以查看整个例子.
Check this repository to see whole example.
在用户更改到另一条路线后,订阅将自动停止.
After user changes to another route, then subcriptions are being automatically stopped.
这篇关于如何在 Meteor 中读取依赖于另一个集合的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!