我想显示来自不同集合的项目提要,按创建日期排序,但我遇到了一些问题。
期望的结果
- 所有集合中的项目应混合在同一页面上,并按日期排序
- 显示屏必须保持 react 性
- 我使用 jQuery Isotope 进行布局
- 结果集有限(例如前 10 条),可以点击“加载更多”按钮来扩大查询限制
我无法正确限制结果集
由于每个集合必须单独查询,我能做的最好的事情就是获取每个集合的前 10 个项目。
在下图中,所需的结果集为红色,绿色轮廓是我得到的结果。
目前,我获取三个游标,合并到一个数组中,排序并保留前十个。
加载更多内容
单击“加载更多”按钮时, react 变量会更新,该变量在订阅中用于限制每个查询的结果。
<小时/>每次加载太多数据的逻辑感觉非常错误。对于查询 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]};
}
最佳答案
这是一个适合您要求的解决方案,但它会给服务器带来更多负载。
您需要确定出版物中每个集合的限制,并相应地发布它们。假设您的限制设置为 10。
- 查找并获取每个集合的前 10 个项目。请注意,您可以在此步骤中使用的 mongo 请求中按日期对它们进行排序。请参阅here和 here
将它们合并到一个数组中,但跟踪它们的来源。例如你可以这样做:
var mergedResults = []; _.each( TenLatestPostArray, function( post){ //we choose the id 1 for the posts mergedResults.push({post.createdAt, 1}) }) _.each( TenLatestArticlesArray, function( article){ //we choose the id 2 for the articles mergedResults.push({article.createdAt, 2}) }) //same for your third collection
您按日期对
mergedResults
进行排序,并对前 10 个结果进行切片- 从数组中提取 id,并计算结果数组中有多少项来自集合 1、2 和 3
您可以按照每个集合的具体限制来发布它:
Meteor.publish('allContent', function(limit) { return [ Posts.find({}, {limit: postsLimit}), Articles.find({}, {limit: articlesLimit}) ]; });
关于javascript - Meteor - 显示多个集合的提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34333484/