How to implement repository design pattern for MongoDB on NestJS
Repository could be injected into the service and it should be included in providers array within the module.
// user.service.ts@Injectable()export class UserService { constructor(private readonly userRepository: UserRepository) {} async findAll(): Promise<User[]> { return this.userRepository.findAll(); }}
// user.repository.ts@Injectable()export class UserRepository { constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {} async findAll(): Promise<User[]> { return this.userModel.find().exec(); }}
// user.module.ts@Module({ imports: [ MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), ], providers: [UserRepository, UserService], exports: [UserService],})export class UserModule {}