Working with a MEVN stack that includes Nestjs, MongoDB (mongoose), I am currently tackling the task of setting up server-side pagination. I've decided to utilize mongoose-aggregate-paginate-v2 for this purpose, but so far, I haven't been able to fully grasp how to implement it within the Nestjs (typescript) and mongoose framework. Any help on this matter would be greatly appreciated.
Referring to the documentation on Nestjs mongoose models and the setup guide for mongoose-aggregate-paginate-v2, here's what I have so far:
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";
// Setting up the plugin:
ContactSchema.plugin(aggregatePaginate);
// Is my interface declaration correct?
interface ContactModel<T extends Document> extends AggregatePaginateResult<T> {}
// How do I create a 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 do I instantiate the model?
let model = connection.model<ContactModel<any>>('Contact', ContactSchema);
return model;
},
inject: ['DATABASE_CONNECTION'],
},
];
As I navigate through the Nestjs, mongoose, and typescript documentation, I'm trying to find a way to incorporate the aggregatePaginate method into my Contact model, allowing me to execute something like:
contact.service.ts
// Setting up the aggregation
const myAggregate = this.contactModel.aggregate(aggregate_options);
const result = await this.contactModel.aggregatePaginate(myAggregate, options); // The problem lies here - aggregatePaginate doesn't exist!
You can check out the work-in-progress code in the following branch: here.
Here are some resources I've referred to during my 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