NestJS中SiteRepository依赖注入失败求助(使用nestjs-typeorm-paginate)
问题解决:NestJS依赖注入失败及分页实现修正
问题根源
你当前的代码同时混用了Mongoose(MongoDB的ODM)和TypeORM(SQL数据库的ORM),但nestjs-typeorm-paginate是专门为TypeORM设计的分页工具,无法直接适配Mongoose。同时你的模块仅配置了Mongoose的实体支持,未注册TypeORM的实体,导致@InjectRepository无法找到对应的依赖。
解决方案
根据你使用的数据库类型,选择以下两种方案之一:
方案1:继续使用Mongoose(MongoDB)实现分页
放弃nestjs-typeorm-paginate,改用Mongoose原生逻辑或专用分页库实现分页:
步骤1:修改Service代码
移除TypeORM相关导入和注入,用Mongoose原生方法实现分页:
import { Model } from 'mongoose'; import { Site, SiteDocument } from "./site.entity"; import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; // 自定义分页返回格式 interface PaginationResult<T> { items: T[]; meta: { totalItems: number; itemCount: number; itemsPerPage: number; totalPages: number; currentPage: number; }; links?: { first?: string; previous?: string; next?: string; last?: string; }; } @Injectable() export class SitesService { constructor( @InjectModel(Site.name) private readonly siteModel: Model<SiteDocument>, ) {} async getSites(page: number, limit: number, route?: string): Promise<PaginationResult<SiteDocument>> { const skip = (page - 1) * limit; const items = await this.siteModel.find().skip(skip).limit(limit).exec(); const totalItems = await this.siteModel.countDocuments().exec(); const result: PaginationResult<SiteDocument> = { items, meta: { totalItems, itemCount: items.length, itemsPerPage: limit, totalPages: Math.ceil(totalItems / limit), currentPage: page, }, }; // 可选:生成分页链接 if (route) { result.links = { first: `${route}?page=1&limit=${limit}`, last: `${route}?page=${result.meta.totalPages}&limit=${limit}`, }; if (page > 1) { result.links.previous = `${route}?page=${page - 1}&limit=${limit}`; } if (page < result.meta.totalPages) { result.links.next = `${route}?page=${page + 1}&limit=${limit}`; } } return result; } }
步骤2:修改Controller代码
@UseGuards(JwtAuthGuard) @Get('get') async index( @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number = 1, @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number = 10, ): Promise<PaginationResult<Site>> { limit = limit > 100 ? 100 : limit; return this.siteService.getSites(page, limit, 'http://cats.com/cats'); }
步骤3:保持现有Module和Entity代码不变
你的Mongoose配置是正确的,无需修改。
方案2:改用TypeORM(适配SQL数据库)
如果使用SQL数据库(如MySQL、PostgreSQL),可改用TypeORM配合nestjs-typeorm-paginate实现:
步骤1:修改Entity代码(改为TypeORM实体)
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class Site { @PrimaryGeneratedColumn() id: number; @Column({ nullable: false }) name: string; @Column({ nullable: true }) site_id: string; @Column({ type: 'int', nullable: true }) properties: number; @Column({ nullable: true }) area: string; @Column({ nullable: true }) address_1: string; @Column({ nullable: true }) address_2: string; @Column({ nullable: true }) address_3: string; @Column({ nullable: true }) postcode: string; @Column({ nullable: true }) site_contact_name: string; @Column({ nullable: true }) site_contact_phone: string; @Column({ nullable: true }) site_contact_email: string; @Column({ nullable: true }) google: string; @Column({ nullable: true }) matterport: string; @Column({ nullable: true }) surveyor: string; @Column({ nullable: true }) survey_date: string; @Column({ nullable: true }) presented: string; }
步骤2:修改Module代码(配置TypeORM)
移除Mongoose配置,添加TypeORM实体注册:
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Site } from "./site.entity"; import { SitesController } from './sites.controller'; import { SitesService } from './sites.service'; @Module({ imports: [ TypeOrmModule.forFeature([Site]) ], providers: [SitesService], controllers: [SitesController] }) export class SitesModule {}
步骤3:修改Service代码(移除Mongoose依赖)
import { Injectable } from '@nestjs/common'; import { Site } from "./site.entity"; import { paginate, Pagination, IPaginationOptions } from "nestjs-typeorm-paginate"; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; @Injectable() export class SitesService { constructor( @InjectRepository(Site) private readonly repository: Repository<Site>, ) {} async getSites(options: IPaginationOptions): Promise<Pagination<Site>> { return paginate<Site>(this.repository, options); } }
步骤4:Controller代码保持不变
你的Controller代码已适配nestjs-typeorm-paginate,无需修改。
内容的提问来源于stack exchange,提问作者Graham Morby
相关产品推荐
相关产品推荐

