Tips for implementing server-side pagination using NestJS

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:

  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

Answer №1

When using NestJs along with mongoose-aggregate-paginate-v2 and mongoose-paginate-v2, conflicts arise due to the plugins utilizing @types/mongoose. This conflict prevents the seamless integration of these plugins in NestJS if @types/mongoose is being used.

This issue came to my attention as I attempted the same setup and discovered that it was not feasible to implement mongoose-aggregate-paginate-v2/mongoose-paginate-v2 until Nestjs addresses the problems with @types/mongoose.

To work around this, I suggest creating a custom function or opting for https://www.npmjs.com/package/mongoose-paginate, as this plugin does not rely on @types/mongoose.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

Customizing the colors of the Input field in the Material UI Text Field component with CSS styling can elevate the overall

import { TextField } from "@mui/material"; import { FunctionComponent } from "react"; interface IProps { type: string; label: string; color: | "error" | "primary" | "secondary" | &quo ...

Update the input type from string to data in MONGO DB format

Is there a way to efficiently convert the inspection_date field in my database from string to date for all objects, similar to the structure below? {"name": "$1 STORE", "address": "5573 ROSEMEAD BLVD", "city": "TEMPLE CITY", "zipcode": "91780", "state": "C ...

Sometimes findOneAndUpdate function in the MEAN stack works intermittently

Currently, I am utilizing the MEAN stack and facing an issue while attempting to update a specific object: { _id : "the id", fields that need updating.... } Below is the function responsible for the update process: function updateById(_id, update, opts ...

transmit data from Node.js Express to Angular application

I am making a request to an OTP API from my Node.js application. The goal is to pass the response from the OTP API to my Angular app. Here is how the API service looks on Angular: sendOtp(params): Observable<any> { return this.apiService.post(&q ...

Stop unnecessary updating of state in a global context within a Functional Component to avoid re-rendering

I am currently working with a Context that is being provided to my entire application. Within this context, there is a state of arrays that store keys for filtering the data displayed on the app. I have implemented this dropdown selector, which is a tree s ...

Establishing a many-to-many relationship in MongoDB (utilizing Mongoid) with the inclusion of extra data fields

Imagine I have two models: User and Project. Each user can be assigned to multiple projects, and each project can have multiple users assigned to it. This represents a typical many-to-many relationship that can be stored as shown below (source): # The use ...

Exploring the combination of MongoDB and NextJS: Easily identify corresponding data regardless of capitalization

This code aims to retrieve and display the latest data on Covid-19 related fatalities, recoveries, and critical cases worldwide. The search function is defined as: const search = (e) => { e.preventDefault() //to prevent page reload cons ...

Validation messages in an Angular application using Typescript are failing to display or disappear sporadically when applied to an HTML form that has

I am currently working on a simple app that retrieves website content from a CMS [Umbraco]. After making an Ajax call, the form comes back to me as plain HTML. I then append the form to the page and use the Angular $compile service to compile the result. T ...

Finding common elements between arrays in MongoDB

There are a few complexities in this situation. I have two collections: test and test1. The documents in each collection have an array field (tags and tags1, respectively) that contain various tags. My goal is to find the intersection of these tags and ret ...

"Encountering issues with Express Validator, specifically .isLength and isEmail functions not

router.post("/", (req, res) => { body("name").isLength({ min: 3 }); // Verifies name length body("email").isEmail(); // Checks email format body("password").isLength({ min: 8 }); // Ensures password length m ...

failure to render updated content after modification of variable

I am facing an issue with triggering a function in the component: componentA.ts html = 'hey'; this.onElementSelected(r => this.change()); public change() { console.log(this.html); if (this.html === 'hey&ap ...

Incorporating unique numbers in the map reduce process

I have a CSV file containing information on which numbers called each other and the details of the calls like duration, time, etc. My goal is to compile all the numbers that a specific number has called into an array. Each element in this array should be ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

Next.js is displaying an error message indicating that the page cannot be properly

Building a Development Environment next.js Typescript Styled-components Steps taken to set up next.js environment yarn create next-app yarn add --dev typescript @types/react @types/node yarn add styled-components yarn add -D @types/styled-c ...

Using object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...

Tips for accurately inputting a global object with an index

I'm in the process of converting a large monolithic JavaScript application to TypeScript and am facing an issue regarding typing a specific module. I am seeking guidance on how to approach this particular problem. It's important to note that I d ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

`Is there a way to dynamically update a nested field object in Mongoose without updating the entire object?`

const userProfile = new Schema({ name: { type: String, default: null }, contacts: { mobileNumber: { countryCode: { type: String, default: null }, digits: { type: String, default: null } }, email: { type: String, default: null }, facebook: { ...

Whenever the return condition is false, make sure to subscribe to the Angular CanActivate Guard

In my UserAccessGuard class, I have a method that captures the current path and compares it to the user's available paths. However, I am facing asynchronous problems because the condition inside the subscribe block causes my Hasaccess variable to rema ...