使用 mongoose 和 nestjs 进行分页 [英] Pagination with mongoose and nestjs

查看:66
本文介绍了使用 mongoose 和 nestjs 进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 mongoose paginate 对一组值进行分页.

Im trying to use mongoose paginate to paginate through an array of values.

class subNotes {
  @Prop()
  Note: string;
  @Prop()
  Date: Date;
}
@Schema()
class Travel extends Document {
  @Prop()
  Country: string;
  @Prop()
  Recommendation: string;
  @Prop()
  Level: number;
  @Prop()
  LevelDescr: string;
  @Prop()
  Date: Date;
  @Prop()
  Notes: [subNotes];
}

出口 const TravelSchema = SchemaFactory.createForClass(Travel);TravelSchema.plugin(mongoosePaginate);所以子注释每周更新一次,并且会有很多信息,我想在 service sice 上分页.为此,我在我的控制器中提供了类似参数的页面和限制

export const TravelSchema = SchemaFactory.createForClass(Travel); TravelSchema.plugin(mongoosePaginate); So subnotes are updated weekly and will have lots of information that i would like to paginate on service sice. For that im providing apage and limit like arguments in my controllers

async createSlugs(
    @Query('page') page = 1,
    @Query('limit') limit = 10,
    @Param('country') country: string,
  ) {
    limit = limit > 100 ? 100 : limit;
    return await this.travelService.getTravelInfo(
      {
        limit: Number(limit),
        page: Number(page),
      },
      country,
    );
  }
}

在服务上,我将我的文档作为分页模型注入并尝试实现这样的服务:

And on the service im injecting my document as a Paginate Model and trying to implement the service like this:

 async getTravelInfo(page = 1, limit = 10, country: string) {
    await this.saveTravelInfo(country);

    const options = {
      page: Number(page),
      limit: Number(limit),
    };

    return await this.notesModel.paginate({ Country: country }, options);
  }

然而分页没有做任何事情,整个国家数据被选中.有什么提示吗?

Yet the paginate isnt doing anything, the entire country data gets selected. Any tip?

async getTravelInfo(page = 1, limit = 10, country: string) {
    await this.saveTravelInfo(country);

    const options = {
      populate: 'subNotes',
      page: Number(page),
      limit: Number(limit),
    };
    console.log(options);

    return await this.notesModel.paginate({ Country: country }, options);
  }

所以限制基本上是复制我的子注释中的内容.如果我设置限制 1,则返回所有 200 个文档.如果我设置限制 2,则返回 400 个文档.:|

So limit is basically duplicating whats inside my subnotes. If i put Limit 1, returns everything aka 200 documents. If i put Limit 2, returns 400 documents. :|

推荐答案

你可以使用 猫鼬分页插件.

一个可能的起点;

import { Inject, Injectable } from '@nestjs/common';
import {
  Connection, Document, PaginateModel, Schema,
} from 'mongoose';
import { InjectConnection } from '@nestjs/mongoose';

import TravelSchema from './travel.schema';

interface IRunAnything extends Document{
  [key: string]: any;
}

type SampleModel<T extends Document> = PaginateModel<T>;

@Injectable()
export default class ProfileRepository {
  constructor(
    @InjectConnection() private connection: Connection
  ) {}

  /**
   * Run the query.
   * The query are just your filters.
   *
   * @param query
   * @param offset
   * @param limit
   */
  async getTravelInfo(query: object, offset = 10, limit = 10) {

    const dynamicModel: SampleModel<IRunAnything> = this.connection.model<IRunAnything>('Travel', this.schema) as SampleModel<IRunAnything>;

    const customLabels = {
      docs: 'nodes',
      page: 'currentPage',
      totalPages: 'pageCount',
      limit: 'perPage',
      totalDocs: 'itemCount',
    };

    return dynamicModel.paginate(query, { customLabels, offset, limit });
  }
}

该解决方案有点陈旧,但您可以在此基础上进行构建并适应您的用例.

The solution is a bit hackish but you can build on it and adapt to your use case.

记得将插件添加到您的架构中.

Remember to add the plugin to your schema.

npm i mongoose-paginate-v2

...
import * as mongoosePaginate from 'mongoose-paginate-v2';

TravelSchema.plugin(mongoosePaginate)

...

这篇关于使用 mongoose 和 nestjs 进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆