Reputation: 835
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?
Upvotes: 3
Views: 4695
Reputation: 3317
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>
) {}
}
Upvotes: 12