Search
Case-insensitive substring match across fields you allow, combined as a safe logical OR.
Build safe MongoDB query objects from API query params. Allow-lists for search, filters, and sorts; predictable pagination; one function between HTTP and the driver.
6+
Query concerns in one API
1
Public entrypoint
0
Framework lock-in
Handlers often reimplement parsing, caps, and allow-lists. Centralise that logic once and keep routes thin: validate input, call buildMongoQuery, pass the result to your data layer.
Each option maps cleanly to documented query parameters or internal API contracts.
Case-insensitive substring match across fields you allow, combined as a safe logical OR.
Only keys in your allow-list become Mongo predicates. Unknown keys are ignored.
Parse sort strings into Mongo sort objects, constrained by allowed field names.
Consistent page, limit, skip, and hard caps so list APIs behave the same everywhere.
Merge tenancy or feature-flag rules alongside static defaults in one place.
Typed configuration and results for handlers, services, and tests.
Anywhere you can read a shallow query object—no ORM required.
No code generation: pass the same shape your adapter already gives you from req.query or equivalent.
npm install mongo-query-toolsTypeScript example
import { buildMongoQuery } from "mongo-query-tools";
const query = {
page: "1",
limit: "20",
search: "john",
sort: "-createdAt",
status: "active",
};
const opts = buildMongoQuery(query, {
searchableFields: ["name", "email"],
allowedFilters: ["status", "role"],
allowedSorts: ["createdAt", "name"],
defaultFilters: { isDeleted: false },
defaultSort: "-createdAt",
maxLimit: 100,
});
db.collection("users")
.find(opts.filter)
.sort(opts.sort)
.skip(opts.skip)
.limit(opts.limit);List searchable fields, allowed filters and sorts, defaults, and max page size next to your route or schema.
Forward the raw query record into buildMongoQuery and pass filter, sort, skip, and limit to MongoDB.
Paste JSON from logs or tests, compare output with production config before you merge.
Read the API reference or try the live playground backed by the published package.