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
exportssection ofCatsModuleand importCatsModulein the other module
My question is how to reference the model in the new module.
I can see:
mongoose.model('Name', MySchema)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 againAny help appreciated!
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>,
) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With