Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement repository design pattern for MongoDB on NestJS

I'm trying to figuring out how to implement repository design pattern on NestJS that using MongoDB and mongoose database

like image 819
Adams Avatar asked Jul 07 '19 16:07

Adams


People also ask

What design pattern does NestJS use?

NestJS Application Using CQRS Design Pattern.

What is repository pattern in NestJS?

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.

How does NestJS connect to MongoDB Atlas?

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.


1 Answers

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 {}
like image 57
Željko Šević Avatar answered Oct 23 '22 11:10

Željko Šević