【发布时间】:2016-03-23 20:32:56
【问题描述】:
我想显示来自不同集合的项目的提要,按创建日期排序,但我遇到了一些问题。
想要的结果
- 所有集合中的项目应混合在同一页面上,按日期排序
- 显示必须保持反应状态
- 我使用 jQuery Isotope 进行布局
- 结果集是有限的(例如前 10 个项目),可以单击“加载更多”按钮来扩大查询限制
我无法正确限制结果集
由于每个集合都必须单独查询,我能做的最好的就是获取每个集合的前 10 个项目。
在下图中,所需的结果集是红色的,绿色的轮廓是我得到的。
目前,我获取三个游标,合并到一个数组中,排序并保留前十个。
加载更多内容
单击“加载更多”按钮时,会更新一个反应变量,该变量在订阅中用于限制每个查询的结果。
那种每次都加载太多数据的逻辑感觉很不对劲。对于查询 3000 个元素、将它们排序到数组中并仅首先显示 1000 个元素的页面会有什么性能影响。
我可能忽略了一种非常简单的方法。我相信这里的一些聪明人可以帮助我找到更好的方法。
一些代码
限于两个集合以使其更简洁
// Server
Meteor.publish('allContent', function(limit) {
return [
Posts.find({}, {limit: limit}),
Articles.find({}, {limit: limit})
];
});
// Client
Template.home.onCreated(function () {
var instance = this;
// initialize the reactive variables
instance.loaded = new ReactiveVar(0);
instance.limit = new ReactiveVar(10);
instance.autorun(function () {
// get the limit
var limit = instance.limit.get();
// subscribe to the posts publication
var subscription = instance.subscribe('allContent', limit);
// if subscription is ready, set limit to newLimit
if (subscription.ready()) {
instance.loaded.set(limit);
}
});
instance.content = function() {
var llimit = instance.loaded.get();
var posts_cursor = Posts.find({}, {limit: llimit});
var articles_cursor = Articles.find({}, {limit: llimit});
var posts_docs = posts_cursor.fetch();
var articles_docs = articles_cursor.fetch();
var docs = posts_docs.concat(articles_docs);
var mix = _.sortBy(docs, function(doc) {return doc.created_at;}).reverse().slice(0,Session.get('limit'));
// Pass the cursors to observe them and re-layout isotope when necessary
return {items: mix, cursors: [services_cursor, posts_cursor]};
}
【问题讨论】:
标签: javascript mongodb meteor