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 🙏

© 2026 – Pkg Stats / Ryan Hefner

mongo-patterns

v1.0.15

Published

A MongoDB repository pattern implementation with TypeScript

Readme

MongoDB Repository Pattern

A flexible and type-safe MongoDB repository pattern implementation for TypeScript applications. This package provides a robust abstraction layer for MongoDB operations with a powerful criteria builder for querying and mutation builder for updates.

Features

  • 🎯 Type-safe MongoDB operations
  • 🔍 Powerful criteria builder for complex queries
  • 🔄 Flexible mutation builder for updates and upserts
  • 📦 Connection management for multiple databases
  • 🛠️ Repository pattern implementation
  • ⚡ Optimized for performance
  • 🧪 Well tested with unit and integration tests
  • 🔄 Support for transaction-like operations
  • 🎨 Clean and maintainable code structure

Installation

npm install mongo-patterns

Quick Start

import { MongoDBRepository, Criteria, Mutation, MongoDBConnectionManager } from 'mongo-patterns';

// Define your entity type
interface User {
  id: string;
  name: string;
  email: string;
  age: number;
}

// Create your repository
class UserRepository extends MongoDBRepository<User> {
  constructor(db: Db) {
    super(db, 'users');
  }
}

// Connect to MongoDB
const db = await MongoDBConnectionManager.connect({
  uri: 'mongodb://localhost:27017',
  dbName: 'myapp'
});

// Initialize repository
const userRepo = new UserRepository(db);

// Create a user
const user = await userRepo.create({
  id:"1",
  name: 'John Doe',
  email: '[email protected]',
  age: 30
});

// Find users using criteria
const users = await userRepo.findMany(
  Criteria.create<User>()
    .where('age', 'GREATER_THAN', 25)
    .andWhere('name', 'LIKE', 'John')
    .orderBy('name', 'ASC')
    .take(10)
    .skip(0)
);

Criteria Builder

The Criteria Builder provides a fluent interface for building complex queries:

const criteria = Criteria.create<User>()
  .where('age', 'GREATER_THAN', 18)
  .andWhere('status', 'IN', ['active', 'pending'])
  .orderBy('createdAt', 'DESC')
  .take(10)
  .skip(0);

Available operators:

  • EQUAL
  • GREATER_THAN
  • LESS_THAN
  • GREATER_THAN_OR_EQUAL
  • LESS_THAN_OR_EQUAL
  • NOT_EQUAL
  • IN
  • NOT_IN
  • LIKE
  • BETWEEN

Mutation Builder

The Mutation Builder provides a powerful interface for building update operations:

// Simple update
const updateMutation = Mutation.update<User>()
  .set('name', 'John Doe')
  .increment('age', 1)
  .push('tags', 'new-tag');

// Upsert operation
const upsertMutation = Mutation.upsert<User>()
  .set('email', '[email protected]')
  .set('status', 'active');

// Array operations
const arrayMutation = Mutation.update<User>()
  .push('roles', ['admin'], { $position: 0 })
  .addToSet('permissions', ['read', 'write'])
  .pull('removedRoles', 'guest');

Available mutation operators:

  • SET - Set a field value
  • UNSET - Remove a field
  • INCREMENT - Increment a numeric field
  • MULTIPLY - Multiply a numeric field
  • PUSH - Add elements to an array
  • PULL - Remove elements from an array
  • ADD_TO_SET - Add unique elements to an array
  • POP - Remove first or last element from an array
  • MIN - Update if new value is less than current
  • MAX - Update if new value is greater than current
  • CURRENT_DATE - Set field to current date
  • RENAME - Rename a field

Array modifiers for PUSH operations:

  • $each - Add multiple elements
  • $position - Insert at specific position
  • $slice - Limit array size after operation
  • $sort - Sort array after operation

Connection Management

The package includes a robust connection management system:

// Connect to multiple databases
const db1 = await MongoDBConnectionManager.connect({
  uri: 'mongodb://localhost:27017',
  dbName: 'db1'
}, 'client1');

const db2 = await MongoDBConnectionManager.connect({
  uri: 'mongodb://localhost:27017',
  dbName: 'db2'
}, 'client2');

// Get database instances
const db1Instance = MongoDBConnectionManager.getDb('client1');
const db2Instance = MongoDBConnectionManager.getDb('client2');

// Disconnect
await MongoDBConnectionManager.disconnect('client1');
await MongoDBConnectionManager.disconnectAll();

Repository Operations

The repository pattern provides standard CRUD operations:

// Create
const created = await repo.create(document);
const manyCreated = await repo.createMany([doc1, doc2]);

// Read
const one = await repo.findOne(criteria);
const many = await repo.findMany(criteria);

// Update with Mutation Builder
const updateMutation = Mutation.update<User>()
  .set('status', 'active')
  .increment('loginCount', 1);
const updated = await repo.updateOne(criteria, updateMutation);

// Upsert with Mutation Builder
const upsertMutation = Mutation.upsert<User>()
  .set('email', '[email protected]')
  .set('createdAt', new Date());
const upserted = await repo.updateOne(criteria, upsertMutation);

// Delete
const deleted = await repo.deleteOne(criteria);
const deletedMany = await repo.deleteMany(criteria);

// Check existence
const exists = await repo.exists(criteria);

Project Structure

.
├── src/
│   ├── core/                 # Core functionality
│   ├── domain/              # Domain interfaces
│   ├── infrastructure/      # Implementation
│   │   └── mongodb/        
│   └── types/               # Type definitions
├── tests/
│   ├── integration/         # Integration tests
│   └── unit/               # Unit tests

Running Tests

# Install dependencies
npm install

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Configuration

The package supports various MongoDB connection options:

interface MongoDBConfig {
  uri: string;
  dbName: string;
  options?: {
    maxPoolSize?: number;
    minPoolSize?: number;
    retryWrites?: boolean;
    connectTimeoutMS?: number;
    socketTimeoutMS?: number;
    ssl?: boolean;
    replicaSet?: string;
    authSource?: string;
  };
}

Development

# Build the project
npm run build

# Run tests
npm test

MongoDB Transactions

The library provides robust transaction support through the MongoDBTransactionManager class, which implements advanced retry strategies and error handling for MongoDB transactions.

Features

  • Parallel and Sequential transaction execution strategies
  • Exponential backoff retry mechanism
  • Automatic handling of transient errors and deadlocks
  • Configurable transaction options
  • Support for mixed operation types within transactions

Basic Usage

const transactionManager = new MongoDBTransactionManager(client, db);

// Execute multiple operations in a transaction
const result = await transactionManager.executeTransaction([
    (session) => repository.create(entity1, { session }),
    (session) => repository.updateOne(criteria, mutation, session),
    (session) => repository.deleteOne(criteria, { session })
]);

if (result.success) {
    console.log('Transaction completed successfully');
} else {
    console.error('Transaction failed:', result.error);
}

Configuration Options

const customTransactionManager = new MongoDBTransactionManager(client, db, {
    maxRetries: 3,
    initialRetryDelay: 100,
    maxRetryDelay: 1000,
    readPreference: 'primary',
    readConcern: 'snapshot',
    writeConcern: { 
        w: 'majority',
        j: true,
        wtimeout: 5000
    }
});

Example Scenarios

  1. Handling Concurrent Updates
const result = await transactionManager.executeTransaction([
    (session) => repository.updateOne(
        Criteria.create<Entity>().where('name', 'EQUAL', 'example'),
        Mutation.update<Entity>().set('value', newValue),
        session
    )
]);
  1. Multiple Operations Across Collections
const result = await transactionManager.executeTransaction([
    (session) => repository1.create(entity1, { session }),
    (session) => repository2.create(entity2, { session }),
    (session) => repository1.updateOne(criteria, mutation, session)
]);
  1. Handling Deadlocks The transaction manager automatically handles deadlocks by retrying in sequential mode:
const result = await transactionManager.executeTransaction([
    (session) => repository.create(entity1, { session }),
    (session) => repository.updateOne(criteria, mutation, session)
]);

// If a deadlock occurs, the transaction will:
// 1. Retry in sequential mode
// 2. Apply exponential backoff
// 3. Return success/failure status with retry information

Error Handling

The transaction manager provides detailed error information:

const result = await transactionManager.executeTransaction([/*...*/]);

console.log({
    success: result.success,
    executionMode: result.executionMode, // 'parallel' or 'sequential'
    retries: result.retries,             // number of retry attempts
    error: result.error                  // error details if failed
});

Best Practices

  1. Keep transactions as short as possible
  2. Avoid mixing read and write operations when possible
  3. Use appropriate read/write concerns for your use case
  4. Handle transaction results appropriately
  5. Monitor retry counts and execution modes for optimization