Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference Mongoose model in different NestJS module

I'm new to NestJS. I'm sure this is a simple question, but I just can't find the answer.

In the nest docs it recommends having one module per model. This involves creating the model using MongooseModule.forFeature:

imports: [MongooseModule.forFeature([{ name: 'Cat', schema: CatSchema }])]

The docs say:

If you also want to use the models in another module, add MongooseModule to the exports section of CatsModule and import CatsModule in the other module

My question is how to reference the model in the new module.

I can see:

  1. How this would be done if the model had been created using mongoose.model('Name', MySchema)
  2. What exports are needed
  3. A question that implies this would be done using import { Model } from 'mongoose'; @InjectModel('name') myModel: Model<MyInterface>), but that feel like it repeats the model creation that is done by MongooseModule.forFeature, because it's combining mongoose Model with the schema again

Any help appreciated!

like image 972
Derek Hill Avatar asked Jan 27 '26 16:01

Derek Hill


1 Answers

So I think that method 3 is the correct one.

According to this comment by @silvelo you do have to separately provide the collection name and the interface when you inject the schema (but not the schema itself):

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: GAME_COLLECTION_NAME, schema: GameSchema },
    ]),
  ],
  controllers: [GamesController],
  components: [GamesService],
  exports: [GamesService, MongooseModule],
})
export class GamesModule implements NestModule {}

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: USER_COLLECTION_NAME, schema: UserSchema },
    ]),
    GamesModule,
    LinksModule,
  ],
  controllers: [UsersController],
  components: [UsersService],
  exports: [UsersService],
})
export class UsersModule implements NestModule {}

@Component()
export class UsersService {
  constructor(
    @InjectModel(GAME_COLLECTION_NAME) private readonly gameModel: Model<Game>,
    @InjectModel(USER_COLLECTION_NAME) private readonly userModel: Model<User>,
  ) {}
}
like image 78
Derek Hill Avatar answered Jan 29 '26 05:01

Derek Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!