observeChanges 可能是您需要的。它允许您将文档发布到特定集合,因此您可以让您的两个出版物(topics 和 popularTopics)从服务器(Topics)上的同一集合中获取数据,但将其发送到不同的集合客户端(例如 Topics 和 PopularTopics)。
这是一个例子:
// globally somewhere
const Topics = new Mongo.Collection('topics');
const PopularTopics = new Mongo.Collection('populartopics');
添加您的发布,使用 observeChanges 将发布的文档发送到客户端上的两个不同集合:
// topics.publications.js
const abstractPublish = function (collectionName, query) {
const cursor = Topics.find(query);
const cursorHandle = cursor.observeChanges({
added(id, fields) {
this.added(collectionName, id, fields);
},
changed(id, fields) {
this.changed(collectionName, id, fields);
},
removed(id) {
this.removed(collectionName, id);
}
});
this.onStop(()=>{
if (cursorHandle) cursorHandle.stop();
});
this.ready();
};
Meteor.publish('topics', function () {
// set up a publication to the "topics" collection
abstractPublish.call(this, 'topics', {});
});
Meteor.publish('popularTopics', function () {
// set up a publication to the "populartopics" collection
abstractPublish.call(this, 'populartopics', {popular: true});
});
然后设置您的模板级订阅:
// topics_main.js
Template.topics_main.onCreated(function () {
this.autorun(() => {
this.subscribe('topics', function () {
Topics.find().fetch(); // returns all topics
);
});
});
在你的热门话题模板中:
// top_topics.js
Template.top_topics.onCreated(function () {
this.autorun(() => {
this.subscribe('popularTopics', function () {
PopularTopics.find().fetch(); // returns only topics that have {popular: true}
);
});
});