mongo-patterns
v1.0.5
Published
A MongoDB repository pattern implementation with TypeScript
Downloads
596
Maintainers
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