The Criteria Pattern is a structural design pattern that encapsulates query conditions into dedicated objects instead of scattering raw filter logic throughout your codebase. InDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/abejarano/ts-mongo-criteria/llms.txt
Use this file to discover all available pages before exploring further.
ts-mongo-criteria, a Criteria instance bundles together filters, sort order, and pagination into a single, composable unit that a repository can translate into a MongoDB query. This means your application layer never touches MongoDB-specific syntax — it speaks in domain terms, while the infrastructure layer handles the translation.
Core components
Criteria
The top-level query object. Holds a
Filters collection, an Order, and optional limit (page size) and page-number parameters. Automatically computes the MongoDB skip value and exposes hasFilters() to check if any conditions are set.Filters
A typed collection of
Filter objects. Build it with Filters.fromValues() from an array of plain Map entries, or use Filters.none() for an unfiltered query.Filter
Represents a single query condition — a
FilterField (column name), a FilterOperator (e.g. EQUAL, GT, BETWEEN), and a FilterValue (the comparison value or complex structure).Order
Encapsulates the sort field and direction (
asc, desc, or none). Factory methods — Order.asc(), Order.desc(), Order.none() — cover the common cases.Class relationship diagram
When to use
When the Criteria Pattern may be overkill:
- Simple static queries — if you always query by a single fixed field (e.g.
findByEmail), a direct repository method is less ceremony. - One-off lookups — migrations, scripts, or debug queries that run once don’t benefit from the extra abstraction layer.
Full working example
Benefits
Type Safety
Every part of a query — the field name, the operator, and the value — is validated at construction time.FilterOperator.fromValue() throws InvalidArgumentError for unrecognised operators, FilterValue validates that BETWEEN and OR values have the expected shape, and Order rejects unknown sort directions. Type errors surface before any network call is made.
Composability
Filters.fromValues() accepts an array of maps, so you can build filter arrays conditionally and compose them freely:
Reusability
Wrap common criteria in factory functions or static methods so the same query logic is never duplicated:Testability
BecauseCriteria is a plain value object with no side effects, unit tests can assert on its properties directly — no MongoDB connection required. Repositories that accept a Criteria parameter are straightforward to test with a stub or in-memory implementation.