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

mongo-patterns

v1.0.5

Published

A MongoDB repository pattern implementation with TypeScript

Downloads

596

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.

Features

  • 🎯 Type-safe MongoDB operations
  • 🔍 Powerful criteria builder for complex queries
  • 📦 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, MongoDBConnectionManager } from 'mongodb-repository-pattern';

// 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

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);
const byId = await repo.findById(id);

// Update
const updated = await repo.updateOne(criteria, update);
const updatedById = await repo.updateById(id, update);

// Delete
const deleted = await repo.deleteOne(criteria);
const deletedById = await repo.deleteById(id);

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