npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-repository-pattern

v1.0.8

Published

A reusable repository pattern with TypeScript and Typegoose

Downloads

117

Readme

How to Use ts-repository-pattern

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.

Installation

  1. Install the ts-repository-pattern package:

    npm install ts-repository-pattern
  2. Install the required dependencies (mongoose, @typegoose/typegoose):

    npm install mongoose @typegoose/typegoose

Project Setup

1. Create Your Typegoose Models

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;
}

2. Extend BaseRepository for Your Models

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));
  }
}

3. Using the Repository

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: '[email protected]' });
};

main().catch((error) => console.error('Error:', error));

4. Available Methods in BaseRepository

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.

Example usage:

// Create a new user
await userRepo.create({ name: 'Alice', email: '[email protected]' });

// 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: '[email protected]' });

// Delete a user by email
await userRepo.deleteOne({ email: '[email protected]' });

Conclusion

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.

Additional Tips

  • You can create repositories for multiple models by extending BaseRepository.
  • Add custom methods in your repositories to handle model-specific operations (e.g., findByEmail in UserRepository).
  • Handle MongoDB connection and error handling properly when working with production environments.

License

This package is licensed under the MIT License. You are free to use, modify, and distribute it.