如何使用 NestJS 提供服务器端分页?

Posted

技术标签:

【中文标题】如何使用 NestJS 提供服务器端分页?【英文标题】:How to provide server-side pagination with NestJS? 【发布时间】:2021-04-16 12:45:44 【问题描述】:

给定一个使用 Nestjs、MongoDB(mongoose) 的 MEVN 堆栈,我正在努力设置服务器端分页。我的方法是使用 mongoose-aggregate-paginate-v2,但我无法从我的研究中提炼出我需要的东西1 以在 Nestjs(typescript) 和 mongoose 的框架内完成这项工作.谢谢你的帮助。。

根据Nestjs mongoose models 和mongoose-aggregate-paginate-v2 setup 的文档,我有以下内容:

contact.provider.ts

import mongoose,  Connection, AggregatePaginateResult, model  from "mongoose";
import  ContactSchema  from "./contact.schema";
import aggregatePaginate from "mongoose-aggregate-paginate-v2";
import  IContact  from "./interfaces/contact.interface";

// notice plugin setup:
ContactSchema.plugin(aggregatePaginate);

// is this correct ?
interface ContactModel<T extends Document> extends AggregatePaginateResult<T> 

// how to create model for factory use ?
export const ContactModel: ContactModel<any> = model<IContact>('Contact', ContactSchema) as ContactModel<IContact>;

export const contactProvider = [
  
    provide: 'CONTACT_MODEL',
    useFactory: (connection: Connection) => 
      // how to instantiate model ?
      let model = connection.model<ContactModel<any>>('Contact', ContactSchema);
      return model;
    ,
    inject: ['DATABASE_CONNECTION'],
  ,
];

我在阅读 Nestjs 文档、mongoose 文档和 typescript 文档之间。在这条路径的某个地方,有一种方法可以在我的 Contact 模型上提供 aggregatePaginate 方法,这样我就可以这样调用:

contact.service.ts

// Set up the aggregation
const myAggregate = this.contactModel.aggregate(aggregate_options);
const result = await this.contactModel.aggregatePaginate(myAggregate, options); // aggregatePaginate does not exist!

审查代码正在进行中 - 可在 this branch 获得。

研究

    Mongoose the Typescript way…? Complete Guide for using Typescript in Mongoose with lean() function Complete guide for Typescript with Mongoose for Node.js MosesEsan/mesan-nodejs-crud-api-with-pagination-filtering-grouping-and-sorting-capabilities Node.js API: Add CRUD Operations With Pagination, Filtering, Grouping, and Sorting Capabilities. API Paging Built The Right Way SO: Mongoose Plugins nestjs SO: Pagination with mongoose and nestjs

【问题讨论】:

这里也一样,如果您想跟踪它,Github 中似乎有一个未解决的问题:github.com/aravindnc/mongoose-paginate-v2/issues/121 【参考方案1】:

NestJs 和 mongoose-aggregate-paginate-v2mongoose-paginate-v2 之间存在冲突> 因为这些插件使用的是@types/mongoose,所以如果你使用@types/mongoose,NestJS 会有冲突。

我告诉你这个是因为我在尝试同样的事情并发现在 Nestjs 使用 @types/mongoose 解决问题之前,实现 mongoo-aggreate-paginate-v2/mongoose-paginate-v2 是不可能的。

我可以建议您自己制作一个自定义函数来执行此操作或使用https://www.npmjs.com/package/mongoose-paginate,因为该插件不需要@types/mongoose。

【讨论】:

谢谢。这是在货架上的自动取款机上,我会回到它并在我这样做时提供我的反馈。再次感谢!

以上是关于如何使用 NestJS 提供服务器端分页?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用服务器端分页实现 Quasar q-table?

如何使用 Datatable 以 POST 类型传递请求正文数据以使用 Javascript 进行服务器端分页

如何在引导表中使用带有 ajax 的服务器端分页?

使用wenzhixin引导表服务器端分页时如何向td元素添加类或属性

使用 ejs 模板和 MYSQL 在节点 js 中的服务器端分页

使用 $resource 的 AngujarJS 服务器端分页总计项目