mongoose Nest无法解析MongoDB的依赖项

knsnq2tg  于 2023-03-30  发布在  Go
关注(0)|答案(1)|浏览(107)

我试图在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: [
    // I also tried different names like: Log, 'Log', Log.name
    MongooseModule.forFeature([{ name: 'Log', schema: LogSchema }]),
  ]
})
export class AuthModule {}

我使用的Mongoose模式代码:

// log.schema.ts

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

@Schema()
export class Log {

  @Prop()
  message: string;
}

export const LogSchema = SchemaFactory.createForClass(Log);

身份验证服务的代码:

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>
  ) {}
...

先谢了!
PS.还看,上面写着LogRepository,但我有LogsRepository

jpfvwuh4

jpfvwuh41#

问题是我在我的项目中使用了@nestjs/sequelize@nestjs/mongoose,在同一个服务中,我试图同时注入sequelize和mongoose模型,但问题是我试图通过使用@nestjs/sequelize中的@InjectModel装饰器来实现这一点

@InjectModel(Session) private readonly sessionRepository: typeof Session,
@InjectModel(Log) private readonly logsRepository: Model<Log>

所以,我已经导入了两个装饰器,但更改了名称:

import { InjectModel } from '@nestjs/sequelize';
import { InjectModel as InjectModelMongo } from '@nestjs/mongoose';

现在一切都很正常

@InjectModel(Session) private readonly sessionRepository: typeof Session,
@InjectModelMongo(InformationLog.name) private readonly logger: Model<InformationLog>

相关问题