NestJS使用mongoose-paginate-v2提示paginate属性不存在如何解决
NestJS 调用 mongoose-paginate-v2 报类型错误解决方案
问题根因
TypeScript 静态类型检测无法自动识别 mongoose 插件挂载到 Model 原型上的自定义方法,mongoose-paginate-v2 插件本身提供了对应的类型声明,替换原生 Model 类型即可解决报错。
修复步骤
修改 Schema 文件,补充分页插件的类型声明
调整car.schema.ts代码,引入插件自带的PaginateModel类型,导出对应带分页方法的 Model 类型:import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; // 导入分页插件及对应类型 import mongoosePaginate, { PaginateModel } from 'mongoose-paginate-v2'; @Schema() export class Car { @Prop({ required: true }) id: number; @Prop({ required: true }) brand: string; @Prop({ required: true }) model: number; @Prop({ required: true }) color: string; } export type CarDocument = Car & Document; // 导出带paginate方法的Model类型 export type CarModel = PaginateModel<CarDocument>; export const CarSchema = SchemaFactory.createForClass(Car); // 注册插件 CarSchema.plugin(mongoosePaginate);修改 Service 层注入的 Model 类型
将原来注入的原生Model<CarDocument>类型替换为上一步定义的CarModel(即PaginateModel<CarDocument>),TS 即可正常识别paginate方法:import { Injectable } from '@nestjs/common'; import { Car, CarDocument, CarModel } from './schemas/car.schema'; import { InjectModel } from '@nestjs/mongoose'; import { Cars } from './cars.mock'; export interface ICarInterface { id: number; brand: string; color: string; model: number; } @Injectable() export class CarService { // 替换注入的Model类型 constructor(@InjectModel(Car.name) private carModel: CarModel) {} private cars = Cars; public async getCars(page: number = 1, limit: number = 10) { // 正常调用paginate方法,无类型报错 return this.carModel.paginate({}, { page, limit }); } }
可选简化写法
如果不想在 Schema 文件额外导出 CarModel 类型,可以直接在 Service 层引入 PaginateModel 做类型声明:
import { PaginateModel } from 'mongoose-paginate-v2'; // 构造函数直接声明类型 constructor(@InjectModel(Car.name) private carModel: PaginateModel<CarDocument>) {}
注意事项
如果修改后仍存在类型识别异常,检查项目 tsconfig.json 中是否开启了 esModuleInterop: true 配置,确保 CommonJS 模块的类型导入正常。
内容的提问来源于stack exchange,提问作者raju
相关产品推荐
相关产品推荐

