Mongoose分页-计算文档总数

5cg8jx4n  于 2023-10-19  发布在  Go
关注(0)|答案(2)|浏览(134)

我正在使用Mongoose paginate搜索和过滤查询一个名为Thought的模式。在我的thoughtindex.ejs模板中,我使用forEach循环在每个页面上显示40条记录:

<% thoughts.docs.forEach(function(thought, i) { %>

有一个显示更多的按钮,点击接下来的40条记录:

<div id="box-show-more" class="box-show-more">
                <button class="show-more" id="showMoreBtn" data-page="<%= thoughts.page + 1 %>">Show More</button>
            </div>

当对记录的作者应用搜索/过滤器时,许多作者的记录少于40条,但当前仍显示“显示更多”按钮。在我的控制器中,分页是这样定义的:

const thoughts = await Thought.paginate(queryObject, {
        page: req.query.page || 1,
        limit: 40,
        sort: { 'createdAt': -1},
        populate: 'likes',
        collation: { locale: "en" }
    });

我想包括一个计数的总文件,所以我可以添加一个 Package 周围显示更多按钮一样,'如果超过40条记录,显示显示更多按钮'。但我不确定如何在分页查询中包含计数。在Mongoose文档中,可以看到有一个名为'totalDocs'的字段,但我不确定在哪里包含它,或者如何从它返回值并在我的.ejs模板中使用。

f4t66c6m

f4t66c6m1#

不确定你使用的是哪个库/插件,但考虑到this library,它应该是相当直接的:

const result = await Thought.paginate(queryObject, {
      page: req.query.page || 1,
      limit: 40,     
      populate: 'likes'       
});

console.log(result.totalDocs);

paginate调用返回的对象将包含一个属性totalDocs,该属性生成集合中与您的查询匹配的文档总数。

holgip5t

holgip5t2#

我做了这个分页服务,可以用在Mongo上。

import mongoose, { Model } from "mongoose";

/**
 * Represents a pagination service.
 * This class helps with managing pagination for a given Mongoose model.
 */

export interface PaginatedResponse {
  result: any[];
  hasNextPage: Boolean;
  hasPreviousPage: Boolean;
}

export default class PaginationService {
  private model: Model<any>;

  /**
   * Create a PaginationService instance.
   * @param {mongoose.Model} model - The Mongoose model to paginate.
   */

  constructor(model: Model<any>) {
    this.model = model;
  }

  private _page_size: number = 10; // Default size is 10

  /**
   * Gets or sets the page size.
   * @default 10
   */

  get page_size(): number {
    return this._page_size;
  }

  set page_size(newSize: number) {
    if (newSize <= 0) {
      throw new Error("Size must be a positive number");
    }
    this._page_size = newSize;
  }

  /**
   * Get Paginated Response
   * Next and Previous page as Boolean
   */

  async getPaginatedResponce(page: number): Promise<PaginatedResponse> {
    const totalDocumentsRecords = await this.model.countDocuments({});

    // Calculate the total number of pages
    const totalPages = Math.ceil(totalDocumentsRecords / this.page_size);

    // Determine if there's page
    const hasNextPage = page < totalPages;
    const hasPreviousPage = page > 1;

    const result = await this.model
      .find()
      .limit(this.page_size)
      .skip((page - 1) * this.page_size)
      .exec();

    const response: PaginatedResponse = {
      result,
      hasNextPage,
      hasPreviousPage,
    };

    return response;
  }
}

如何使用?是这样

import PaginationService, {
  PaginatedResponse,
} from "@/services/Pagination/Pagination";

const pagination = new PaginationService(anyMongoModel);
    pagination.page_size = 2;

let page = 1

let paginated_response: PaginatedResponse = await pagination.getPaginatedResponse(page);

你可以调整它来处理更多的场景。

相关问题