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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@abejarano/ts-mongodb-criteria

v1.3.0

Published

Patrón Criteria para consultas MongoDB en TypeScript

Downloads

230

Readme

🔍 TypeScript MongoDB Criteria Pattern

npm version GitHub Package TypeScript MongoDB License: MIT Node.js Tests

A robust, type-safe implementation of the Criteria Pattern for MongoDB queries in TypeScript. Build complex database queries dynamically with a fluent, composable API designed following Domain-Driven Design (DDD) and Clean Architecture principles.

📚 Table of Contents

🎯 Overview

The Criteria Pattern is a powerful design pattern that enables dynamic query construction without writing raw database queries. This library provides a type-safe, MongoDB-specific implementation that helps you:

  • Build queries dynamically based on runtime conditions
  • Maintain type safety throughout your query construction
  • Compose and reuse query components across your application
  • Separate concerns between query logic and data models
  • Test queries easily with a mockable interface

What is the Criteria Pattern?

The Criteria pattern encapsulates query logic in a structured, object-oriented way. Instead of building query strings or objects directly, you compose Criteria objects that represent your search intentions. This approach provides flexibility, reusability, testability, and type safety.

✨ Key Features

🔒 Type Safety First

  • Full TypeScript support with strict typing
  • Compile-time validation of query structure
  • IntelliSense support for all operations

🧩 Flexible Query Building

  • Support for all common MongoDB operators (EQUAL, NOT_EQUAL, GT, GTE, LT, LTE, CONTAINS, NOT_CONTAINS)
  • NEW: OR operator for complex logical combinations
  • Composable filters that can be combined and reused
  • Dynamic query construction based on runtime conditions

📊 Advanced Querying

// Simple equality
{ status: { $eq: "active" } }

// Complex OR conditions
{ $or: [
  { name: { $regex: "john" } },
  { email: { $regex: "john" } }
]}

// Range queries
{ age: { $gte: 18 }, price: { $lte: 999.99 } }

🎯 MongoDB Optimized

  • Native MongoDB 6.0+ support
  • Efficient query generation
  • Automatic index-friendly query structure

📦 Zero Dependencies

  • Only peer dependencies (MongoDB driver)
  • Lightweight bundle size

🏗️ Clean Architecture

  • Repository pattern implementation
  • Domain-driven design principles
  • Separation of concerns

📦 Installation

# Using npm
npm install @abejarano/ts-mongodb-criteria

# Using yarn
yarn add @abejarano/ts-mongodb-criteria

# Using pnpm
pnpm add @abejarano/ts-mongodb-criteria

Peer Dependencies

# MongoDB driver (required)
npm install mongodb@^6.0.0

# TypeScript (for development)
npm install -D typescript@^5.0.0

System Requirements

  • Node.js: 20.0.0 or higher
  • TypeScript: 5.0.0 or higher (for development)
  • MongoDB: 6.0.0 or higher

🚀 Quick Start

import {
  Criteria,
  Filters,
  Order,
  Operator,
  MongoRepository,
} from "@abejarano/ts-mongodb-criteria"

// 1. Create filters using a simple Map-based syntax
const filters = [
  new Map([
    ["field", "status"],
    ["operator", Operator.EQUAL],
    ["value", "active"],
  ]),
  new Map([
    ["field", "age"],
    ["operator", Operator.GTE],
    ["value", "18"],
  ]),
]

// 2. Build criteria with filters, sorting, and pagination
const criteria = new Criteria(
  Filters.fromValues(filters),
  Order.desc("createdAt"),
  20, // limit
  1 // page
)

// 3. Use with your MongoDB repository
class UserRepository extends MongoRepository<User> {
  collectionName(): string {
    return "users"
  }
}

const userRepo = new UserRepository()
const users = await userRepo.searchByCriteria(criteria)

Your First Query in 30 Seconds:

// Find active users over 18, sorted by creation date
const activeAdultUsers = new Criteria(
  Filters.fromValues([
    new Map([
      ["field", "status"],
      ["operator", Operator.EQUAL],
      ["value", "active"],
    ]),
    new Map([
      ["field", "age"],
      ["operator", Operator.GTE],
      ["value", "18"],
    ]),
  ]),
  Order.desc("createdAt"),
  10, // Get 10 results
  1 // First page
)

const results = await repository.searchByCriteria(activeAdultUsers)

📖 Documentation

📖 Complete Documentation

🎯 Key Concepts

1. Criteria - The main query builder

const criteria = new Criteria(filters, order, limit?, page?)

2. Filters - Collection of filter conditions

const filters = Filters.fromValues([...filterMaps])

3. Order - Sorting specification

const order = Order.desc("createdAt") // or Order.asc("name")

4. Operators - Available filter operations

  • EQUAL, NOT_EQUAL - Exact matching
  • GT, GTE, LT, LTE - Range operations
  • BETWEEN - Inclusive range with lower and upper bounds
  • CONTAINS, NOT_CONTAINS - Text search
  • OR - Logical OR combinations

🆕 OR Operator Example

import { OrCondition } from "@abejarano/ts-mongodb-criteria"

// Search across multiple fields
const searchConditions: OrCondition[] = [
  { field: "name", operator: Operator.CONTAINS, value: "john" },
  { field: "email", operator: Operator.CONTAINS, value: "john" },
]

const filters = [
  new Map([
    ["field", "search"],
    ["operator", Operator.OR],
    ["value", searchConditions],
  ]),
]

// Generates: { $or: [
//   { name: { $regex: "john" } },
//   { email: { $regex: "john" } }
// ]}

⏱️ BETWEEN Operator Example

// Filter users created between two dates
const filters = [
  new Map([
    ["field", "createdAt"],
    ["operator", Operator.BETWEEN],
    ["value", { start: new Date("2024-01-01"), end: new Date("2024-01-31") }],
  ]),
]

const criteria = new Criteria(Filters.fromValues(filters), Order.none())

// Generates: { createdAt: { $gte: 2024-01-01, $lte: 2024-01-31 } }

🧪 Testing

The library includes comprehensive test coverage (30/30 tests passing).

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

🤝 Contributing

We welcome contributions! Please follow these guidelines:

Development Setup

# Clone the repository
git clone https://github.com/abejarano/ts-mongo-criteria.git
cd ts-mongo-criteria

# Install dependencies
yarn install

# Run tests
yarn test

# Build the project
yarn build

Contribution Process

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Ensure all tests pass (yarn test)
  5. Commit using conventional commits (git commit -m 'feat: add amazing feature')
  6. Push to your branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

📄 License

This project is licensed under the MIT License. See the LICENSE file for details.


👨‍💻 Author

Ángel Bejarano
📧 [email protected]
🐙 GitHub
🏢 Jaspesoft


⭐️ If this project helps you, please give it a star on GitHub!

🤝 Questions or suggestions? Open an issue or start a discussion.

📢 Follow us for updates and new features!