#Error importing service with a mongoose model dependency

1 messages · Page 1 of 1 (latest)

boreal hare
#

I'm trying to import UserService into AuthService but I get this error:

Nest can't resolve dependencies of the UserService (?). Please make sure that the argument UserModel at index [0] is available in the AuthModule context.

Potential solutions:
- Is AuthModule a valid NestJS module?
- If UserModel is a provider, is it part of the current AuthModule?
- If UserModel is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing UserModel */ ]
  })

Minimum reproduction repository:
https://github.com/Krak798/nest-mongoose-model-import-error

How can I solve this problem?

sullen minnow
#

You are importing userService, but userService injects something in your case it is mongodb injectable.

#

you have several options

#

First options its moving mongodb module into module that contains both modules auth and user. And use forRoot method of MongooseModule.

#

Second is import UserModule in AuthModule and export userService in export array of UserModule

boreal hare
# sullen minnow Second is import UserModule in AuthModule and export userService in export array...

Thanks for replying. But I tried that too.

auth.module.ts

@Module({
  controllers: [AuthController],
  providers: [AuthService, UserService],
  imports: [JwtModule, UserModule],
})
export class AuthModule {}

user.module.ts

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: User.name,
        schema: UserSchema,
      },
    ]),
  ],
  providers: [UserService],
  controllers: [UserController],
  exports: [UserService],
})
export class UserModule {}
#

And the error is still the same.

#

I will provide a minimum reproduction repository soon.

boreal hare
#

Importing the MongooseModule with the UserSchema into AuthModule works, but I don't know if that's the expected behaviour.

analog ingot
#

@InjectModel(User.name) private userModel: Model<User> should change <User> to <UserDocument>

boreal hare
plush flare
# boreal hare Thanks for replying. But I tried that too. `auth.module.ts` ```ts @Module({ c...

since the UserService is already exported from the UserModule, you don't need to register it as a provider again in the AuthModule

@Module({
  controllers: [AuthController],
- providers: [AuthService, UserService],
+ providers: [AuthService],
  imports: [JwtModule, UserModule],
})
export class AuthModule {}

AuthModule is trying to find the dependencies of the UserService, and that is where the error is originating from