Chris Rutherford
Chris Rutherford

Reputation: 1672

NestJS Service throwing error with @InjectModel

I have a nestJs app I'm working on and I cannot figure out why this is happening. I'm using the mongoose module to get my model prepped for the service, and I have it defined and exported from the schema file.

I've defined the model with the import for the mongoose module.

@Module({
    imports: [MongooseModule.forFeature([{name: 'Message', schema: MessageSchema}])],
    providers: [MessageService],
    exports: [MessageService]
})

and in the service I'm using @InjectModel() to inject the message model to the service like this: (with Model being imported from mongoose, and Message being imported from the schema file.

constructor(
    @InjectModel('Message') private readonly messageModel: Model<Message>
  )

But I still have this error:

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

What am I missing?

Upvotes: 0

Views: 1585

Answers (1)

Rohit Gupta
Rohit Gupta

Reputation: 3259

I had the same problem, What I would do is basically export MongooseModule as well in the decorator options.

@Module({
    imports: [MongooseModule.forFeature([{name: 'Message', schema: MessageSchema}])],
    providers: [MessageService],
    exports: [MongooseModule,MessageService] // <-- added MongooseModule here
})
export class MessageModule {}

Upvotes: 5

Related Questions