问题
Given a MEVN stack using Nestjs, MongoDB(mongoose) I am working to setup server-side pagination. My approach is to use the mongoose-aggregate-paginate-v2, but I have not been able to distill what I need from my research1 to make this work within the framework of Nestjs(typescript) and mongoose. Thanks for the assist..
Following documentation on Nestjs mongoose models, and mongoose-aggregate-paginate-v2 setup, I have the following:
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'],
},
];
I am between reading the Nestjs documentation, mongoose documentation, and typescript documentation. Somewhere along this path there is a way to provide the aggregatePaginate method on my Contact model, so that I can call like:
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!
Review code in progress - available on this branch.
Research
- 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
回答1:
There is a conflict between NestJs and mongoose-aggregate-paginate-v2 and mongoose-paginate-v2 because those plugins are using @types/mongoose, so, NestJS has conflicts if you use @types/mongoose.
I tell you this because i was trying the same thing and figure it out that is not posible to implement mongoo-aggreate-paginate-v2/mongoose-paginate-v2 till Nestjs solve the issues with @types/mongoose.
I can recommend you make a custom function by your own to do that or use https://www.npmjs.com/package/mongoose-paginate because that plugin does not require @types/mongoose.
来源:https://stackoverflow.com/questions/65669164/how-to-provide-server-side-pagination-with-nestjs