流星过滤的出版物,其数量有限制,总计数会跳过

时间:2019-02-27 15:58:14

标签: mongodb meteor meteor-publications

给出一个经过筛选和分页的流星出版物,如何获得应用了经过筛选的流星总数?

客户代码:

import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { Track } from 'meteor/tracker';

import { Posts } from '/imports/api/posts/posts.js';

import './posts.html';

Template.App_posts.onCreated(function() {
  this.subscribe('posts.all', new Date(), 0);

  Tracker.autorun(() => {
    let postCount = Posts.find({}).count();
    console.log(postCount); // 10
  });
});

服务器代码:

import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { Posts } from '../posts.js';

const postsPerPage = 10;

Meteor.publish('posts.all', function(date, page = 0) {
  if (!Meteor.userId()) throw new Meteor.Error('Unauthorised');

  check(date, Date);
  check(page, Number);

  let query = {
    userId: Meteor.userId()
  };

  let options = {};

  if (date) {
    query.createdAt = date;
  }

  options.limit = postsPerPage;
  options.skip = page * postsPerPage;

  let cursor = Posts.find(query, options);

  console.log(cursor.count()); // 100

  return cursor;
});

这会返回给定日期和页面的预期帖子,但问题是知道筛选出的总数。

假设有1000个帖子,其中100个帖子适用于该日期和用户。如果一次只返回10个,我如何得到100的计数?

1 个答案:

答案 0 :(得分:0)

我认为您应该使用tmeasday:publish-counts related post

在服务器上,您应该执行以下操作:

Meteor.publish('posts.numberOfPosts', function(date) {
   if (!this.userId){
       return this.ready();
   } 
   check(date, Date);

   let query = {
      userId: this.userId
   };
   if (date) {
     query.createdAt = date;
   }
   Counts.publish(this, 'all-posts', Posts.find(query));
}

在客户端上: Counts.get('All-orders')

实际上,您也可以将此订阅放置在“ posts.all”中:

Meteor.publish('posts.all', function(date, page = 0) {
  if (!Meteor.userId()) throw new Meteor.Error('Unauthorised');

  check(date, Date);
  check(page, Number);

  let query = {
    userId: Meteor.userId()
  };

  let options = {};

  if (date) {
    query.createdAt = date;
  }

  options.limit = postsPerPage;
  options.skip = page * postsPerPage;

  let cursor = Posts.find(query, options);
  // https://github.com/percolatestudio/publish-counts#noready
  Counts.publish(this, 'all-posts', Posts.find(query), {noReady: true});

  return cursor;
});