This guide will walk you through the steps to integrate and use the ts-repository-pattern
package with Typegoose and MongoDB in your TypeScript project.
-
Install the
ts-repository-pattern
package:npm install ts-repository-pattern
-
Install the required dependencies (
mongoose
,@typegoose/typegoose
):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:
// 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
.
// 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<User> {
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:
// 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<T>): Promise<number>
: Count documents matching the query. -
find(query: Partial<T>): Promise<T[]>
: Find documents matching the query. -
findOne(query: Partial<T>): Promise<T>
: Find a document matching the query. -
create(data: T): Promise<T>
: Create a new document. -
updateOne(query: Partial<T>, updateData: Partial<T>): Promise<boolean>
: Update a document matching the query. -
deleteOne(query: Partial<T>): Promise<boolean>
: Delete documents matching the query.
// 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
. - Add custom methods in your repositories to handle model-specific operations (e.g.,
findByEmail
inUserRepository
). - 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.