nestjs-typegoose icon indicating copy to clipboard operation
nestjs-typegoose copied to clipboard

Suggestion: "Nest can't resolve dependencies of the Model" due to connectionName

Open dereekb opened this issue 5 years ago • 1 comments

I'm new to using Nestjs/Typegoose and ran into the issue where I kept getting the following issue:

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

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

Eventually I realized that I had accidentally set a connectionName in my configuration:

@Module({
  imports: [
...
    // Typegooose
    TypegooseModule.forRootAsync({
      connectionName: "mongodb",
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        useNewUrlParser: true,
        useUnifiedTopology: true,
        uri: configService.get<string>("MONGODB_URI")
      })
    }),
...

...which suddenly clicked because the models were registering with the default/non-named connection.

This is mostly a cautionary tale. In retrospect, the Nestjs DI system. was telling me the DefaultTypegooseConnection didn't exist, when I thought it had.

I'm not sure if it's possible to add some other sort of warning (if one is necessary) or a way in which the generated DI Tokens aren't entirely connected behind magic from the connectionName string.

dereekb avatar Oct 26 '20 01:10 dereekb

I will try to take a look at this at some point in the future (most likely December) since I am really swamped with college work.

From a glance, I think it might be possible if NestJS exposes a way to catch DI errors/warnings. If there is no solid solution, I could add a note to the docs to say: "Make sure you created the typegoose connection properly" if you get this error.

kpfromer avatar Oct 28 '20 22:10 kpfromer