我正在尝试从集合中加载最新的帖子,同时加载同一篇帖子的所有评论。该集合具有引用,而不是将整个文档存储在彼此内部:
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。
我想我可以从模板中做到这一点,但当然,如果我查询评论集合,它仍然是空的。但我确实有 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()
};
}
});
检查这个存储库 https://github.com/parhelium/stackoverflow-last-post-with-comments查看整个示例。
用户更改到另一条路线后,订阅将自动停止。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)