javascriptnode.jsmongodbdependency-injectionnestjs

Generic mongoose dynamic module cannot inject options


I wanna have a dynamic module which should take care of registering mongoose for me. Right now I have a problem with injecting the options asynchronously when I am invoking MongooseModule.forRootAsync({...}), it says it cannot inject the Symbol(MONGO_MODULE_OPTIONS) and I do not get it why.

I have exported the Symbol(MONGO_MODULE_OPTIONS) here:

const asyncProviders = this.createAsyncProviders(options);
const databaseOptionsModule = {
  module: MongoModule,
  imports: [...(options.imports ?? [])],
  providers: [...asyncProviders],
  exports: [MONGO_MODULE_OPTIONS],
};

I also tried to change gears and use the MongooseModule.forRootAsync in the same dynamic module: https://github.com/kasir-barati/bugs/blob/832140936a45f945963468bfde5d6570e880cfd5/src/mongo/mongo.module.ts

But that did not help either. When I run the e2e tests I keep getting this error message:

$ pnpm test:e2e

> bugs@0.0.1 test:e2e /home/kasir/projects/bugs
> jest --config ./test/jest-e2e.json

 FAIL  test/app.e2e-spec.ts
  AppController (e2e)
    ✕ / (GET) (6 ms)

  ● AppController (e2e) › / (GET)

    Nest can't resolve dependencies of the MongooseModuleOptions (?). Please make sure that the argument Symbol(MONGO_MODULE_OPTIONS) at index [0] is available in the MongooseCoreModule context.

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

Any suggestion other than adding a sync version of register API which I know will work


Solution

  • So the way that I resolved this issue was by just using the ConfigurableModuleBuilder helper class. Basically I needed to create a wrapper around MongooseModule and then pass the options from MongoModule to it.

    Here is how I did it: https://github.com/kasir-barati/bugs/blob/028caf4819903d71a79cf2495659604483617317/src/mongo/mongo.module.ts