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

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

根据Nestjs mongoose modelsmongoose-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 获得。

研究

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

【问题讨论】:

标签: mongodb typescript mongoose nestjs


【解决方案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。

【讨论】:

  • 谢谢。这是在货架上的自动取款机上,我会回到它并在我这样做时提供我的反馈。再次感谢!
猜你喜欢
  • 2019-09-22
  • 2019-08-23
  • 2019-11-17
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2019-01-05
  • 2016-05-04
相关资源
最近更新 更多