A reusable repository pattern with TypeScript and Typegoose
npm install ts-repository-patternts-repository-patternThis guide will walk you through the steps to integrate and use the ts-repository-pattern package with Typegoose and MongoDB in your TypeScript project.
1. Install the ts-repository-pattern package:
``bash`
npm install ts-repository-pattern
2. Install the required dependencies (mongoose, @typegoose/typegoose):
`bash`
npm install mongoose @typegoose/typegoose
First, define your data model using Typegoose. For example, if you are working with a User model, define it as follows:
`typescript
// src/entities/user.ts
import { prop } from '@typegoose/typegoose';
export class User {
@prop({ required: true })
public name!: string;
@prop({ required: true })
public email!: string;
}
`
Next, create a repository class for your User model by extending the BaseRepository provided by ts-repository-pattern.
`typescript
// src/repositories/user-repository.ts
import { getModelForClass } from '@typegoose/typegoose';
import { BaseRepository } from 'ts-repository-pattern';
import { User } from '../entities';
export class UserRepository extends BaseRepository
constructor() {
super(getModelForClass(User));
}
}
`
Now, you can use your UserRepository to perform database operations. Here is an example of how to use it in your application:
`typescript
// src/app.ts
import { UserRepository } from './repositories/user-repository';
const main = async () => {
// Connect to the database
// Instantiate the repository
const userRepo = new UserRepository();
// Create a new user
const newUser = await userRepo.create({ name: 'John Doe', email: 'john@example.com' });
};
main().catch((error) => console.error('Error:', error));
`
Your BaseRepository class includes the following methods for common CRUD operations:
- countDocument(query?: Partial
- find(query: Partial
- findOne(query: Partial
- create(data: T): Promise
- updateOne(query: Partial
- deleteOne(query: Partial
#### Example usage:
`typescript
// Create a new user
await userRepo.create({ name: 'Alice', email: 'alice@example.com' });
// Find all users with the name "Alice"
const users = await userRepo.find({ name: 'Alice' });
// Find one user with the id "1"
const users = await userRepo.findOne({ id: 1 });
// Count the number of users
const userCount = await userRepo.countDocument();
// Update a user's email
await userRepo.updateOne({ name: 'Alice' }, { email: 'alice@newmail.com' });
// Delete a user by email
await userRepo.deleteOne({ email: 'alice@example.com' });
`
By following these steps, you can easily implement a repository pattern for your MongoDB models using TypeScript and Typegoose. You can extend BaseRepository to add custom logic and methods for each model, making your codebase clean, reusable, and maintainable.
- You can create repositories for multiple models by extending BaseRepository.findByEmail
- Add custom methods in your repositories to handle model-specific operations (e.g., in UserRepository`).
- Handle MongoDB connection and error handling properly when working with production environments.
This package is licensed under the MIT License. You are free to use, modify, and distribute it.