9

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!

Derek Hill
  • 5,965
  • 5
  • 55
  • 74

1 Answers1

12

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>,
  ) {}
}
Derek Hill
  • 5,965
  • 5
  • 55
  • 74