Repository Pattern in Node.js: A Practical TypeScript and Mongoose Example

The Repository Design Pattern helps Node.js developers separate database operations from business logic. Instead of writing Mongoose queries directly inside controllers or services, you place data-access operations in a dedicated repository and expose them through a clear interface.

In this tutorial, we’ll build a user-management API using Node.js, Express, TypeScript, and Mongoose. You’ll learn how to define a repository interface, implement database operations, connect the repository to a service layer, and test business logic with a mocked repository – without requiring a live database for every unit test.

The pattern can make a codebase easier to maintain and test when its layers have clear responsibilities. However, it doesn’t automatically make database queries faster or guarantee that switching databases will be effortless. Those benefits depend on how the application is designed and implemented.

A repository layer is not necessary for every application. For a small CRUD service with limited data-access requirements, it may add more abstraction than value. It becomes more useful when data access needs a clear boundary, multiple services share persistence operations, or business logic needs to be tested independently of the database.


1. Project Setup and Folder Structure

First, set up your project using Express, TypeScript, and Mongoose (our ORM for MongoDB).

A. Initialization and Dependencies

Open your terminal and execute the following commands:

# 1. Initialize the project directory
mkdir node-repo-api && cd node-repo-api
npm init -y

# 2. Install application dependencies
npm install express mongoose dotenv

# 3. Install development dependencies
npm install -D typescript ts-node @types/node @types/express nodemon

# 4. Initialize TypeScript configuration
npx tsc --init --rootDir src --outDir dist --esModuleInterop --resolveJsonModule --lib es2022 --module commonjs

B. The Clean Folder Structure

Create the following folder and file structure inside the root directory:

node-repo-api/
src/
├── models/
│   └── user.model.ts
├── domain/
│   └── IUserRepository.ts
├── repositories/
│   └── UserRepository.ts
├── services/
│   └── UserService.ts
├── controllers/
│   └── UserController.ts
├── routes/
│   └── user.routes.ts
├── dtos/
│   └── CreateUser.dto.ts
├── errors/
│   └── ConflictError.ts
├── utils/
│   └── asyncHandler.ts
└── app.ts

Add a .env file in the project root:

MONGO_URI=mongodb://127.0.0.1:27017/node-repo-api
PORT=3333

2. The Model and the Repository Design Pattern Classes

The Repository Pattern provides a clean separation of concerns. We define a contract before writing the database code.

A. Model Definition (src/models/user.model.ts)

Define the Mongoose schema for the User entity.

import { Schema, model, InferSchemaType, HydratedDocument } from 'mongoose';

const UserSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
      lowercase: true,
      trim: true,
    },
    isActive: {
      type: Boolean,
      default: true,
      index: true,
    },
  },
  {
    timestamps: true,
  }
);

// Infer the user data shape from the schema.
export type User = InferSchemaType<typeof UserSchema>;
export type UserDocument = HydratedDocument<User>;

const UserModel = model('User', UserSchema);

export default UserModel;

B. Repository Interface (src/domain/IUserRepository.ts)

Define the contract that the Service layer will depend on.

import type { User, UserDocument } from '../models/user.model';

export type CreateUserData = Pick<User, 'name' | 'email'>;

export type UpdateUserData = Partial<
  Pick<User, 'name' | 'email' | 'isActive'>
>;

export interface IUserRepository {
  findById(id: string): Promise<UserDocument | null>;

  findAllActive(): Promise<UserDocument[]>;

  create(data: CreateUserData): Promise<UserDocument>;

  update(id: string, data: UpdateUserData): Promise<UserDocument | null>;

  findActivePaginated(page: number, limit: number): Promise<UserDocument[]>;
}

The interface defines the operations that the service is allowed to request. The repository implementation must provide every method declared here, using compatible parameter and return types. This keeps the service independent of Mongoose-specific query methods.

C. Repository Implementation (src/repositories/UserRepository.ts)

Implement the interface, containing all Mongoose-specific code.

import type { IUserRepository, CreateUserData, UpdateUserData } from '../domain/IUserRepository';
import UserModel from '../models/user.model';
import type { UserDocument } from '../models/user.model';

export class UserRepository implements IUserRepository {
  public async findById(id: string): Promise<UserDocument | null> {
    return UserModel.findById(id)
      .select('name email isActive')
      .exec();
  }

  public async findAllActive(): Promise<UserDocument[]> {
    return UserModel.find({ isActive: true })
      .select('name email')
      .exec();
  }

  public async create(data: CreateUserData): Promise<UserDocument> {
    return UserModel.create(data);
  }

  public async update(
    id: string,
    data: UpdateUserData
  ): Promise<UserDocument | null> {
    return UserModel.findByIdAndUpdate(id, data, {
      new: true,
      runValidators: true,
    }).exec();
  }

  public async findActivePaginated(
    page: number,
    limit: number
  ): Promise<UserDocument[]> {
    const validPage = Math.max(1, Math.floor(page));
    const validLimit = Math.min(100, Math.max(1, Math.floor(limit)));

    return UserModel.find({ isActive: true })
      .select('name email')
      .skip((validPage - 1) * validLimit)
      .limit(validLimit)
      .exec();
  }
}

3. Service and Controller Layers

These layers are now clean and database-agnostic.

A. Service Layer (src/services/UserService.ts)

Handles Business Logic and depends only on the IUserRepository interface.

First, create src/dtos/CreateUser.dto.ts with:

import type { CreateUserData } from '../domain/IUserRepository';

export type CreateUserDto = CreateUserData;

Then:

import type { IUserRepository } from '../domain/IUserRepository';
import type { CreateUserDto } from '../dtos/CreateUser.dto';
import { ConflictError } from '../errors/ConflictError';

export class UserService {
  constructor(
    private readonly userRepository: IUserRepository
  ) {}

  public getActiveUsers() {
    return this.userRepository.findAllActive();
  }

  public async registerUser(userData: CreateUserDto) {
    try {
      return await this.userRepository.create(userData);
    } catch (error: unknown) {
      if (
        typeof error === 'object' &&
        error !== null &&
        'code' in error &&
        error.code === 11000
      ) {
        throw new ConflictError('A user with this email already exists');
      }

      throw error;
    }
  }
}

However, in this example, the service does not call Mongoose directly, but the shared user types are still derived from the Mongoose model. A stricter database-independent architecture would define domain entities and repository contracts separately from persistence-specific document types, then map database documents to those domain entities.

B. Controller Layer (src/controllers/UserController.ts)

Handles HTTP requests and delegates all work to the Service Layer.

Put this in src/errors/ConflictError.ts:

export class ConflictError extends Error {
  public readonly statusCode = 409;

  constructor(message: string) {
    super(message);
    this.name = 'ConflictError';
  }
}

Then:

import type { Request, Response } from 'express';
import type { UserService } from '../services/UserService';

export class UserController {
  constructor(private readonly userService: UserService) {}

  public getActiveUsers = async (req: Request, res: Response) => {
    const users = await this.userService.getActiveUsers();
    return res.status(200).json({ data: users });
  };

  public createNewUser = async (req: Request, res: Response) => {
    const newUser = await this.userService.registerUser(req.body);
    return res.status(201).json({
      id: newUser._id,
      email: newUser.email,
    });
  };
}

The error handler converts known application errors into appropriate HTTP responses. For unexpected errors, return a generic server-error message to the client and log the original error on the server. Avoid exposing stack traces, database details, or internal configuration in production responses.


4. Routing and Application Entry

This section connects the HTTP paths to the Controller methods.

A. Async Handler (src/utils/asyncHandler.ts)

import type {
  Request,
  Response,
  NextFunction,
  RequestHandler,
} from 'express';

type AsyncRouteHandler = (
  req: Request,
  res: Response,
  next: NextFunction
) => Promise<unknown>;

export const asyncHandler = (
  handler: AsyncRouteHandler
): RequestHandler => {
  return (req, res, next) => {
    Promise.resolve(handler(req, res, next)).catch(next);
  };
};

B. Route Definition (src/routes/user.routes.ts)

import { Router } from 'express';
import { UserController } from '../controllers/UserController';
import { UserService } from '../services/UserService';
import { UserRepository } from '../repositories/UserRepository';
import { asyncHandler } from '../utils/asyncHandler';

const router = Router();

// Wire the layers together in one place.
const userRepository = new UserRepository();
const userService = new UserService(userRepository);
const userController = new UserController(userService);

router.get('/active', asyncHandler(userController.getActiveUsers));
router.post('/', asyncHandler(userController.createNewUser));

export default router;

C. Application Setup (src/app.ts)

Set up the Express server and register the routes. (You’ll need to set up a MongoDB connection for production, omitted here for brevity.)

import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import userRoutes from './routes/user.routes';

dotenv.config();

const app = express();
const PORT = Number(process.env.PORT ?? 3333);
const MONGO_URI = process.env.MONGO_URI;

app.use(express.json());
app.use('/api/v1/users', userRoutes);

app.use(
  (
    error: Error & { statusCode?: number },
    req: express.Request,
    res: express.Response,
    next: express.NextFunction
  ) => {
    if (res.headersSent) {
      return next(error);
    }

    const statusCode = error.statusCode ?? 500;

    return res.status(statusCode).json({
      error: statusCode === 500
        ? 'Internal server error'
        : error.message,
    });
  }
);

async function startServer() {
  if (!MONGO_URI) {
    throw new Error('MONGO_URI is not configured in the environment');
  }

  await mongoose.connect(MONGO_URI);

  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
  });
}

startServer().catch((error: unknown) => {
  console.error('Failed to start server:', error);
  process.exit(1);
});

5. Run and Test

One benefit of separating the service from the database implementation is that you can test service behavior with a mocked repository. The following Jest example checks that the service delegates the request to its repository. The mock uses simplified objects for this focused unit test; it does not test Mongoose, MongoDB connectivity, or database queries.

Test your fully layered API using the terminal or a GUI client.

A. Setup for Development

A typical development script using tsx and nodemon could be:

{
  "scripts": {
    "dev": "nodemon --watch src --ext ts --exec tsx src/app.ts"
  }
}

Start the server:

npm run dev

B. Testing with cURL (Terminal/Bash)

The base URL for the User API is http://localhost:3333/api/v1/users.

Test 1: GET /api/v1/users/active

curl -X GET http://localhost:3333/api/v1/users/active

Expected Output: 200 OK and a JSON array of active users.

Test 2: POST /api/v1/users (Create)

# Note: Escaping double quotes is needed for Bash/CMD
curl -X POST http://localhost:3333/api/v1/users \
     -H "Content-Type: application/json" \
     -d '{"name": "Dmitri", "email": "dmitri@example.com"}'

Expected Output: 201 Created and a JSON object containing the new user’s id and email.

C. Testing with Postman (GUI)

  1. For POST:
    • Set HTTP Method to POST.
    • Set Request URL: http://localhost:3333/api/v1/users
    • Go to the Body tab, select raw, and choose JSON.
    • Paste the JSON data and click Send.
  2. For GET:
    • Set HTTP Method to GET.
    • Set Request URL: http://localhost:3333/api/v1/users/active
    • Click Send.

The pain point most teams hit after adopting this pattern: how do you unit test the Service layer without spinning up MongoDB? Since UserService depends only on the IUserRepository interface, you can inject a fully mocked repository in tests:

// tests/UserService.test.ts
import { UserService } from '../src/services/UserService';
import type { IUserRepository } from '../src/domain/IUserRepository';

describe('UserService', () => {
  it('returns active users from the repository', async () => {
    const mockRepo = {
      findAllActive: jest.fn().mockResolvedValue([
        { name: 'Dmitri', email: 'dmitri@example.com' },
      ]),
    } as unknown as IUserRepository;

    const service = new UserService(mockRepo);
    const result = await service.getActiveUsers();

    expect(result).toHaveLength(1);
    expect(result[0]).toMatchObject({
      name: 'Dmitri',
      email: 'dmitri@example.com',
    });
    expect(mockRepo.findAllActive).toHaveBeenCalledTimes(1);
  });
});

This test runs without a database connection because it tests the service in isolation. Separate integration tests are still needed to verify that the repository interacts with MongoDB correctly.


Why It’s Better?

CriteriaWithout a RepositoryWith a Repository
Code separationData-access logic may be mixed into controllers or servicesData-access operations are grouped behind a defined interface
MaintainabilityDatabase changes may require edits across multiple layersChanges can often be isolated within the repository and its related code
Unit testingServices that directly call Mongoose are harder to test in isolationServices can be tested using a mocked repository
Query performanceDepends on how database queries are implementedDepends on query design, indexing, selected fields, and other optimizations
Database portabilityDatabase-specific code may be spread across the applicationA repository can centralize database-specific code, but switching databases still requires compatible implementations and testing

The Repository Design Pattern gives Node.js applications a defined boundary between business logic and database operations. In this example, the controller handles HTTP requests, the service coordinates application behavior, and the repository contains the Mongoose queries.

This separation makes the service easier to test with a mock repository and gives database-related changes a clearer place in the codebase. It does add another layer, so the pattern is most useful when an application benefits from that separation rather than simply adding abstraction to every small project.

To extend this example, consider adding request validation, pagination endpoints, repository integration tests, and a consistent error-handling strategy. These additions will help turn the basic example into a more complete API.

You’ll find some writing on clean software architecture in this section. Thank you for reading!


Useful Links

Mizanur Islam Laskar
Mizanur Islam Laskar

Scrum Master and Project Manager with 6+ years of experience leading software delivery across international teams. A Certified Scrum Master (CSM) with a track record of achieving 95% on-time delivery, 90% client satisfaction, and reducing cycle times by up to 30%. Experienced in guiding teams, improving Agile ways of working, and keeping engineering delivery aligned with business goals. Skilled in project governance, risk and dependency management, delivery forecasting, backlog refinement, and stakeholder communication. With a strong technical background in PHP and JavaScript technologies, AWS, and databases, I can bridge the gap between business needs and engineering decisions, helping teams make informed trade-offs and deliver practical solutions.

More About Me | Explore My Projects

Leave a Reply