I'm trying to figuring out how to implement repository design pattern on NestJS that using MongoDB and mongoose database
NestJS Application Using CQRS Design Pattern.
Repository patternTypeORM supports the repository design pattern, so each entity has its own repository. These repositories can be obtained from the database data source. To continue the example, we need at least one entity. Let's define the User entity. user.entity.ts.
Go to your MongoDB Atlas Account, go to your cluster and click the Connect button. Copy the string replacing the “username” for the one that you created in your MongoDB Cluster, also replace the “<password>” and finally replace “test” for the name of your collection inside the Database you created before.
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 {}
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