Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

mongodb - How to provide server-side pagination with NestJS?

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

  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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...