You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nest.js集成MongoDB时依赖无法解析错误求助

Nest.js 中使用 MongoDB 时的依赖注入错误

错误信息

Nest can't resolve dependencies of the AuthService (SessionRepository, ?). Please make sure that the argument LogRepository at index [1] is available in the AuthModule context.

相关代码

app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from '@auth/auth.module';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `../../.env.${process.env.NODE_ENV}`
    }),
    MongooseModule.forRoot(process.env.MONGO_DB_LOGS),
    AuthModule
  ]
})
export class AppModule {}

auth.module.ts

import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { SequelizeModule } from '@nestjs/sequelize';
import { Session } from '@models/session.model';
import { MongooseModule } from '@nestjs/mongoose';
import { Log, LogSchema } from '@mongo-schemas/log.schema';

@Module({
  providers: [AuthService],
  exports: [AuthService],
  controllers: [AuthController],
  imports: [
    // 我试过不同的名称,比如: Log, 'Log', Log.name
    MongooseModule.forFeature([{ name: 'Log', schema: LogSchema }]),
  ]
})
export class AuthModule {}

log.schema.ts

import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';

@Schema()
export class Log {

  @Prop()
  message: string;
}

export const LogSchema = SchemaFactory.createForClass(Log);

auth.service.ts

import { Log } from '@mongo-schemas/log.schema';
import { Model } from 'mongoose';

@Injectable()
export class AuthService {
  constructor(
    @InjectModel(Session) private readonly sessionRepository: typeof Session,
    @InjectModel(Log) private readonly logsRepository: Model<Log>
  ) {}
...
}

补充说明

错误信息中显示的是LogRepository,但我实际使用的是LogsRepository。


解决方案

1. 补全 Session 模型的导入

AuthService中注入了Session模型,但AuthModule未导入对应的 Sequelize 模块,导致 Nest 无法解析该依赖。在auth.module.ts的imports数组中添加:

SequelizeModule.forFeature([Session]),

2. 统一 Mongoose 模型命名规则

确保MongooseModule.forFeature中的name参数与@InjectModel的入参完全一致。由于Log类通过@Schema()装饰,Log.name会返回字符串'Log',推荐用以下写法保证一致性:

// auth.module.ts
MongooseModule.forFeature([{ name: Log.name, schema: LogSchema }]),

// auth.service.ts
@InjectModel(Log.name) private readonly logsRepository: Model<Log>

3. 验证依赖安装与版本兼容性

确认已正确安装相关依赖:

npm install @nestjs/mongoose mongoose
npm install -D @types/mongoose

同时检查@nestjs/core与@nestjs/mongoose版本是否匹配,版本差异可能导致注入异常。

4. 清理缓存并重启项目

缓存可能引发依赖解析问题,执行以下命令后重启项目:

rm -rf node_modules package-lock.json
npm install
npm run start:dev

内容的提问来源于stack exchange,提问作者dokichan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:32:14