I am trying to use MongoDB in my Nest.js project. It seems like I have installed everything correctly, but I keep getting this error:
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.
Here is how it looks like in the code:
// 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 {}
Code of the authentication module:
// 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 {}
Code of Mongoose schema that I use:
// log.schema.ts
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
@Schema()
export class Log {
@Prop()
message: string;
}
export const LogSchema = SchemaFactory.createForClass(Log);
Code of the authenticatoin service:
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>
) {}
...
Thanks in advance!
PS. Also see, it says LogRepository
, but I have LogsRepository
.
I have found the issue. The thing is that I am using @nestjs/sequelize
and @nestjs/mongoose
in my project, and in the same service I was trying to inject this both sequelize and mongoose models, but the issue is that I was trying to do this by using @InjectModel
decorator from @nestjs/sequelize
@InjectModel(Session) private readonly sessionRepository: typeof Session,
@InjectModel(Log) private readonly logsRepository: Model<Log>
So, I have imported both decorators, but have changed the name:
import { InjectModel } from '@nestjs/sequelize';
import { InjectModel as InjectModelMongo } from '@nestjs/mongoose';
And now everything works perfectly fine:
@InjectModel(Session) private readonly sessionRepository: typeof Session,
@InjectModelMongo(InformationLog.name) private readonly logger: Model<InformationLog>