Search code examples
mongoosenestjshook

Hello, I set up a hook on nestJS using MongooseModule, but I'm having trouble injecting third-party services


import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Commande, CommandeSchema } from 'src/commande/commande.model';

@Module({
    imports: [
        MongooseModule.forFeatureAsync([
            {
                name: 'Commande',
                imports: [SharedModule],
                inject: [MyService],
                useFactory: async (myService: MyService) => {
                    const schema = CommandeSchema;
                    schema.post('save', async function (doc) {
                        const commande = doc as unknown as Commande;
                        await myService.savingLivraison(commande);
                    });
                    return schema;
                },
            },
        ]),],
    providers: [MyService],
    exports: [MyService]
})
export class SharedModule { }

when I do that the SharedModule module does not load while I load it well in the AppModule and when I remove the exports line in the shared module I have the error: `[Nest] 25850 - 08/06/2023 17:02:52 ERROR [ExceptionHandler] Nest can't resolve dependencies of the CommandeModel (DatabaseConnection, ?, MyService).

what I want is to be able to use the myService in the context of MongooseModule


Solution

  • You've created a circular dependency of the SharedModule on itself. The SharedModule needs to import the MongooseModule, but the MongooseModule needs to import the SharedModule. What you need to do is move the MyService to a module outside of the SharedModule which can then be imported by the SharedModule and the MongooseModule, and then the SharedModule can re-export this new module to make the MyService available anywhere theSharedModule is imported