首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Meteor filtered with limit和skip with total count

Meteor filtered with limit和skip with total count
EN

Stack Overflow用户
提问于 2019-02-27 23:58:14
回答 1查看 127关注 0票数 0

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

客户端代码:

代码语言:javascript
复制
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
  });
});

服务器代码:

代码语言:javascript
复制
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的计数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-28 01:08:41

我认为您应该使用tmeasday:publish-counts https://github.com/percolatestudio/publish-counts

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

代码语言:javascript
复制
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-order’)

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

代码语言:javascript
复制
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;
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54909536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档