2

I have a Nestjs and MongoDB application.

auth.module.ts -

@Module({
  imports: [
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
  ],
  controllers: [AuthController],
  providers: [AuthService],
})
export class AuthModule {}

auth.service.ts -

@Injectable()
export class AuthService {
  // Inject User model into AuthService
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  getUser(username: string) {
    const user = this.userModel.find({ name: username });
    return user;
  }

  
}

I have a UserSchema created using @nestjs/mongoose and mongoose.

According to the docs, when I import a schema using MongooseModule in a Module, that schema is available to use in that particular module only.

What if I want access to multiple models in my module and service? Is there a way for that?

How do I Inject multiple models into a service?

Rajiv
  • 3,346
  • 2
  • 12
  • 27
vaibhav deep
  • 655
  • 1
  • 8
  • 27

1 Answers1

10

here is the solution:-

auth.module.ts

@Module({
  imports: [
    MongooseModule.forFeature([
       { name: 'User', schema: UserSchema },
       { name: 'Comment', schema: CommentSchema }
    ]),
  ],
  controllers: [AuthController],
  providers: [AuthService],
})
export class AuthModule {}

auth.service.ts

export class AuthService {
  constructor(
    @InjectModel('User') private readonly userModel: Model<IUser>,
    @InjectModel('Comment') private readonly CommentModel: Model<IComment>
  ) {}
}
Rajiv
  • 3,346
  • 2
  • 12
  • 27
Nilesh Patel
  • 3,193
  • 6
  • 12