mongoose-query-find 3.0.9 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +483 -83
- package/dist/aggregate.d.ts +130 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +352 -6
- package/dist/aggregate.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://github.com/jsdev-robin/mongoose-query-find/blob/main/LICENSE)
|
|
5
5
|
[](https://mongoosejs.com)
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Two fluent, chainable, allowlisted query builders for Mongoose — **`QueryFind`** for simple `Model.find()` queries, and **`QueryAggregate`** for anything that needs joins, grouping, timezone-aware date filtering, or advanced pagination. Both are driven directly from URL query parameters with zero boilerplate.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -43,16 +43,35 @@ A fluent, chainable query builder for Mongoose that handles filtering, global se
|
|
|
43
43
|
- [Builder Methods](#builder-methods-1)
|
|
44
44
|
- [.allowFields()](#allowfieldsfields-string-1)
|
|
45
45
|
- [.dateFields()](#datefieldsfields-string)
|
|
46
|
+
- [.objectIdFields()](#objectidfieldsfields-string)
|
|
46
47
|
- [.filter()](#filter-1)
|
|
47
48
|
- [.where()](#whereconditions-1)
|
|
48
49
|
- [.range()](#rangefield-string-preset-rangepreset)
|
|
50
|
+
- [Custom Range Methods](#custom-range-methods)
|
|
51
|
+
- [.rangeCustomDay()](#rangecustomdayfield-string-date-string)
|
|
52
|
+
- [.rangeBetween()](#rangebetweenfield-string-custom-customdaterangeinput)
|
|
53
|
+
- [.rangeLastNDays()](#rangelastndaysfield-string-days-number)
|
|
54
|
+
- [.rangeLastNHours()](#rangelastnhoursfield-string-hours-number)
|
|
55
|
+
- [.rangeHours()](#rangehoursfield-string-custom-customhourrangeinput)
|
|
56
|
+
- [.rangeCustom()](#rangecustomfield-string-custom-customdatetimerangeinput)
|
|
57
|
+
- [.excludeSoftDeleted()](#excludesoftdeletedfield-deletedat)
|
|
58
|
+
- [.whereIf()](#whereifcondition-conditions)
|
|
49
59
|
- [.globalSearch()](#globalsearchfields-string-1)
|
|
50
60
|
- [.sort()](#sort-1)
|
|
51
61
|
- [.project()](#projectdefaultprojection-string--recordstring-0--1)
|
|
52
62
|
- [.lookup()](#lookupopts-lookupoptions)
|
|
63
|
+
- [.computeField()](#computefieldname-string-expression-unknown)
|
|
53
64
|
- [.addStage()](#addstagestage-pipelinestage)
|
|
54
|
-
- [Terminal
|
|
65
|
+
- [Terminal & Utility Methods](#terminal--utility-methods)
|
|
55
66
|
- [.paginate()](#paginatecachedtotal-number)
|
|
67
|
+
- [.paginateCursor()](#paginatecursoropts-cursorpaginateoptions)
|
|
68
|
+
- [.count()](#count)
|
|
69
|
+
- [.distinct()](#distinctfield-string)
|
|
70
|
+
- [.stats()](#statsspecs-statspec)
|
|
71
|
+
- [.stream()](#stream)
|
|
72
|
+
- [.explain()](#explainverbosity)
|
|
73
|
+
- [.clone()](#clone)
|
|
74
|
+
- [.debugPipeline()](#debugpipeline)
|
|
56
75
|
- [Recipes](#recipes)
|
|
57
76
|
- [Pipeline Stage Ordering](#pipeline-stage-ordering)
|
|
58
77
|
- [Security](#security-1)
|
|
@@ -119,16 +138,21 @@ queryFind(query, queryString, options?);
|
|
|
119
138
|
```
|
|
120
139
|
|
|
121
140
|
| Parameter | Type | Description |
|
|
122
|
-
| ------------- |
|
|
123
|
-
| `query` | `Query<TRawDocType[], TRawDocType>`
|
|
124
|
-
| `queryString` | `QueryParams`
|
|
125
|
-
| `options` | `QueryFindOptions` _(optional)_
|
|
141
|
+
| ------------- | ------------------------------------ | ------------------------------------------------------ |
|
|
142
|
+
| `query` | `Query<TRawDocType[], TRawDocType>` | A Mongoose query, e.g. `Model.find()` |
|
|
143
|
+
| `queryString` | `QueryParams` | The parsed URL query object, e.g. `req.query` |
|
|
144
|
+
| `options` | `QueryFindOptions` _(optional)_ | Configuration options (see [Options](#options) below) |
|
|
126
145
|
|
|
127
146
|
### Options
|
|
128
147
|
|
|
129
|
-
| Option
|
|
130
|
-
|
|
|
131
|
-
| `maxTimeMS`
|
|
148
|
+
| Option | Type | Default | Description |
|
|
149
|
+
| ----------------------- | ----------------------------------------- | ------- | -------------------------------------------------------------------------- |
|
|
150
|
+
| `maxTimeMS` | `number` | `5000` | Max milliseconds MongoDB may spend on each query. Pass `0` to disable. |
|
|
151
|
+
| `slowQueryThresholdMS` | `number` | `maxTimeMS` | Threshold above which `onSlowQuery` fires. |
|
|
152
|
+
| `maxLimit` | `number` | `100` | Hard cap on `?limit=`. |
|
|
153
|
+
| `lean` | `boolean` | `true` | Whether `.find()` calls `.lean()` for faster plain-object reads. |
|
|
154
|
+
| `onSlowQuery` | `(info: SlowQueryInfo) => void` | — | Callback fired when a query exceeds `slowQueryThresholdMS`. |
|
|
155
|
+
| `onSanitizeDrop` | `(path: string, value: unknown) => void` | — | Callback fired whenever sanitization drops a client-supplied value. |
|
|
132
156
|
|
|
133
157
|
---
|
|
134
158
|
|
|
@@ -309,13 +333,13 @@ GET /users?page=2&limit=20
|
|
|
309
333
|
## Query Parameter Reference
|
|
310
334
|
|
|
311
335
|
| Parameter | Example | Description |
|
|
312
|
-
| ----------- |
|
|
313
|
-
| `page` | `?page=3`
|
|
314
|
-
| `limit` | `?limit=25`
|
|
315
|
-
| `sort` | `?sort=-createdAt,name`
|
|
316
|
-
| `fields` | `?fields=name,email`
|
|
317
|
-
| `q` | `?q=john`
|
|
318
|
-
| _(any key)_ | `?role=admin&age[gte]=18`
|
|
336
|
+
| ----------- | -------------------------- | -------------------------------------------------------- |
|
|
337
|
+
| `page` | `?page=3` | Page number (default: `1`, min: `1`) |
|
|
338
|
+
| `limit` | `?limit=25` | Documents per page (default: `10`, max: `100`) |
|
|
339
|
+
| `sort` | `?sort=-createdAt,name` | Sort fields; prefix `-` for descending (max: 5 fields) |
|
|
340
|
+
| `fields` | `?fields=name,email` | Comma-separated fields to include in the response |
|
|
341
|
+
| `q` | `?q=john` | Global search term (max: 200 chars) |
|
|
342
|
+
| _(any key)_ | `?role=admin&age[gte]=18` | Field-level filters processed by `.filter()` |
|
|
319
343
|
|
|
320
344
|
---
|
|
321
345
|
|
|
@@ -376,6 +400,9 @@ import {
|
|
|
376
400
|
QueryParams,
|
|
377
401
|
PaginatedResult,
|
|
378
402
|
QueryFindOptions,
|
|
403
|
+
QueryFindError,
|
|
404
|
+
QueryFindValidationError,
|
|
405
|
+
SlowQueryInfo,
|
|
379
406
|
} from 'mongoose-query-find';
|
|
380
407
|
```
|
|
381
408
|
|
|
@@ -400,7 +427,20 @@ interface PaginatedResult<T> {
|
|
|
400
427
|
}
|
|
401
428
|
|
|
402
429
|
interface QueryFindOptions {
|
|
403
|
-
maxTimeMS?: number;
|
|
430
|
+
maxTimeMS?: number; // default: 5000
|
|
431
|
+
slowQueryThresholdMS?: number; // default: maxTimeMS
|
|
432
|
+
maxLimit?: number; // default: 100
|
|
433
|
+
lean?: boolean; // default: true
|
|
434
|
+
onSlowQuery?: (info: SlowQueryInfo) => void;
|
|
435
|
+
onSanitizeDrop?: (path: string, value: unknown) => void;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
interface SlowQueryInfo {
|
|
439
|
+
elapsedMs: number;
|
|
440
|
+
filter: Record<string, unknown>;
|
|
441
|
+
sort: Record<string, 1 | -1>;
|
|
442
|
+
page: number;
|
|
443
|
+
limit: number;
|
|
404
444
|
}
|
|
405
445
|
```
|
|
406
446
|
|
|
@@ -408,17 +448,17 @@ interface QueryFindOptions {
|
|
|
408
448
|
|
|
409
449
|
## Security
|
|
410
450
|
|
|
411
|
-
| Protection | Detail
|
|
412
|
-
|
|
|
413
|
-
| **NoSQL injection**
|
|
414
|
-
| **Banned operators**
|
|
415
|
-
| **ReDoS**
|
|
416
|
-
| **Oversized search**
|
|
417
|
-
| **Deep nesting DoS**
|
|
418
|
-
| **Page size DoS**
|
|
419
|
-
| **Sort abuse**
|
|
420
|
-
| **Runaway queries**
|
|
421
|
-
| **Sensitive field leakage**
|
|
451
|
+
| Protection | Detail |
|
|
452
|
+
| ---------------------------- | -------------------------------------------------------------------------------------------- |
|
|
453
|
+
| **NoSQL injection** | Allowlist enforced on filters, sort, and projection via `.allowFields()` |
|
|
454
|
+
| **Banned operators** | `$where`, `$expr`, `$function`, and others are rejected recursively at any nesting depth |
|
|
455
|
+
| **ReDoS** | Search terms are regex-escaped before compilation |
|
|
456
|
+
| **Oversized search** | `?q=` capped at 200 characters |
|
|
457
|
+
| **Deep nesting DoS** | Filter object nesting capped at depth 5 |
|
|
458
|
+
| **Page size DoS** | `limit` hard-capped at 100 |
|
|
459
|
+
| **Sort abuse** | Sort fields hard-capped at 5 |
|
|
460
|
+
| **Runaway queries** | `maxTimeMS` applied to both count and find (default: 5s) |
|
|
461
|
+
| **Sensitive field leakage** | `?fields=` projection stripped against allowlist |
|
|
422
462
|
|
|
423
463
|
---
|
|
424
464
|
|
|
@@ -443,27 +483,36 @@ ISC © [jsdev.robin@gmail.com](mailto:jsdev.robin@gmail.com)
|
|
|
443
483
|
|
|
444
484
|
# QueryAggregate
|
|
445
485
|
|
|
446
|
-
A fluent, allowlisted **aggregation-pipeline** builder for Mongoose (`^8 || ^9`), built on `Model.aggregate()`. It mirrors the same safety model as `QueryFind` — allowlisted filter fields, sanitized/rejected operators, capped pagination — but adds `$lookup` joins, `$group`,
|
|
486
|
+
A fluent, allowlisted **aggregation-pipeline** builder for Mongoose (`^8 || ^9`), built on `Model.aggregate()`. It mirrors the same safety model as `QueryFind` — allowlisted filter fields, sanitized/rejected operators, capped pagination — but adds `$lookup` joins, `$group`, timezone-aware date filtering, custom date/hour ranges, keyset pagination, and one-round-trip dashboard stats.
|
|
447
487
|
|
|
448
488
|
## QueryAggregate Overview
|
|
449
489
|
|
|
450
|
-
`QueryFind` is built on `Model.find()` and can't express joins or grouping. `QueryAggregate` solves that while keeping the same guardrails:
|
|
490
|
+
`QueryFind` is built on `Model.find()` and can't express joins or grouping. `QueryAggregate` solves that while keeping the same guardrails, plus a lot more:
|
|
451
491
|
|
|
452
492
|
- Allowlisted filter/sort/projection fields
|
|
453
493
|
- Recursive sanitization of client input (drops class instances, functions, over-deep nesting)
|
|
454
494
|
- Banned-operator rejection (`$where`, `$expr`, `$function`, `$accumulator`, `$map`, `$reduce`, `$filter`)
|
|
455
495
|
- Capped pagination (`limit`, `page`)
|
|
456
|
-
-
|
|
496
|
+
- Timezone-aware date coercion, `$lookup` joins, arbitrary developer-authored pipeline stages via `.addStage()`
|
|
497
|
+
- Single-round-trip pagination via `$facet`
|
|
498
|
+
- **New:** six custom date-range methods (arbitrary day, arbitrary span, rolling N-days/N-hours, hour-of-day windows, absolute datetime windows)
|
|
499
|
+
- **New:** `count()`, `distinct()`, and `stats()` for cheap metrics without fetching a data page
|
|
500
|
+
- **New:** `stream()` for memory-safe large exports, and `paginateCursor()` for keyset pagination on huge collections
|
|
501
|
+
- **New:** `explain()`, `debugPipeline()`, and `clone()` for debugging and query reuse
|
|
457
502
|
|
|
458
503
|
## When to use QueryAggregate vs QueryFind
|
|
459
504
|
|
|
460
505
|
| Need | Use |
|
|
461
|
-
|
|
|
462
|
-
| Simple filter/sort/paginate on one collection
|
|
463
|
-
| Joining another collection (`$lookup`)
|
|
464
|
-
| Grouping / rollups / computed fields (`$group`, `$addFields`)
|
|
465
|
-
| Client filters need to respect the caller's local timezone
|
|
466
|
-
|
|
|
506
|
+
| ---------------------------------------------------------------- | ------------------ |
|
|
507
|
+
| Simple filter/sort/paginate on one collection | `QueryFind` |
|
|
508
|
+
| Joining another collection (`$lookup`) | `QueryAggregate` |
|
|
509
|
+
| Grouping / rollups / computed fields (`$group`, `$addFields`) | `QueryAggregate` |
|
|
510
|
+
| Client filters need to respect the caller's local timezone | `QueryAggregate` |
|
|
511
|
+
| A custom day / date span / rolling window / hour-of-day filter | `QueryAggregate` |
|
|
512
|
+
| Dashboard totals (sum/avg/count) without fetching a page | `QueryAggregate` |
|
|
513
|
+
| Very large collections where `$skip` pagination gets slow | `QueryAggregate` |
|
|
514
|
+
| Streaming a large export without buffering it in memory | `QueryAggregate` |
|
|
515
|
+
| You need a custom developer-defined pipeline stage | `QueryAggregate` |
|
|
467
516
|
|
|
468
517
|
## Installation
|
|
469
518
|
|
|
@@ -513,30 +562,30 @@ new QueryAggregate<T>(model, queryString, options?);
|
|
|
513
562
|
```
|
|
514
563
|
|
|
515
564
|
| Parameter | Type | Description |
|
|
516
|
-
| ------------- |
|
|
517
|
-
| `model` | `Model<T>`
|
|
518
|
-
| `queryString` | `QueryParams`
|
|
519
|
-
| `options` | `QueryAggregateOptions`
|
|
565
|
+
| ------------- | ------------------------ | -------------------------------------------------- |
|
|
566
|
+
| `model` | `Model<T>` | A Mongoose model |
|
|
567
|
+
| `queryString` | `QueryParams` | Parsed URL query object, e.g. `req.query` |
|
|
568
|
+
| `options` | `QueryAggregateOptions` | Configuration options (see below), all optional |
|
|
520
569
|
|
|
521
570
|
### `QueryAggregateOptions`
|
|
522
571
|
|
|
523
|
-
| Option | Type | Default | Description
|
|
524
|
-
|
|
|
525
|
-
| `timezone`
|
|
526
|
-
| `maxTimeMS`
|
|
527
|
-
| `slowQueryThresholdMS`
|
|
528
|
-
| `maxLimit`
|
|
529
|
-
| `allowDiskUse`
|
|
530
|
-
| `weekStartsOn`
|
|
531
|
-
| `onSlowQuery`
|
|
532
|
-
| `onSanitizeDrop`
|
|
572
|
+
| Option | Type | Default | Description |
|
|
573
|
+
| ------------------------ | ------------------------------------------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
574
|
+
| `timezone` | `string` | `'Asia/Dhaka'` | IANA timezone for interpreting client-supplied local dates. Invalid values fall back to the default (validated once at construction, never throws mid-query). |
|
|
575
|
+
| `maxTimeMS` | `number` | `5000` | Max time MongoDB may spend per query. `0` disables. |
|
|
576
|
+
| `slowQueryThresholdMS` | `number` | `maxTimeMS` | Threshold above which `onSlowQuery` fires. |
|
|
577
|
+
| `maxLimit` | `number` | `100` | Hard cap on `?limit=`. |
|
|
578
|
+
| `allowDiskUse` | `boolean` | `false` | Forwarded to `.allowDiskUse()` — enable for large sort/group pipelines. |
|
|
579
|
+
| `weekStartsOn` | `0–6` | `6` (Saturday) | Used by `.range('thisWeek')`. |
|
|
580
|
+
| `onSlowQuery` | `(info: SlowQueryInfo) => void` | — | Callback fired when a query exceeds `slowQueryThresholdMS`. |
|
|
581
|
+
| `onSanitizeDrop` | `(path: string, value: unknown) => void` | — | Callback fired whenever sanitization drops a value (bad nesting, non-plain value). |
|
|
533
582
|
|
|
534
583
|
## Timezone Handling
|
|
535
584
|
|
|
536
585
|
MongoDB always stores/compares dates in UTC. Clients think and filter in local time — `?createdAt=2026-09-01` means "Sept 1st in the caller's timezone," not UTC midnight.
|
|
537
586
|
|
|
538
587
|
- `fromZonedTime(localString, tz)` → exact UTC instant for a wall-clock time in `tz`. Used to turn a client-supplied local date into the correct `$gte`/`$lt` UTC range in `$match`.
|
|
539
|
-
- `toZonedTime(utcDate, tz)` → wall-clock `Date` for `tz`. Used to compute "what day is it right now, in the caller's timezone" for `.range()` presets.
|
|
588
|
+
- `toZonedTime(utcDate, tz)` → wall-clock `Date` for `tz`. Used to compute "what day is it right now, in the caller's timezone" for `.range()` presets and the rolling-N-days custom range.
|
|
540
589
|
|
|
541
590
|
The timezone is a **per-request** value, typically sourced from a header:
|
|
542
591
|
|
|
@@ -546,14 +595,14 @@ const timezone = (req.headers['x-timezone'] as string) ?? 'Asia/Dhaka';
|
|
|
546
595
|
|
|
547
596
|
An invalid/unknown IANA timezone string (bad header, typo) never throws — it's validated once at construction (`resolveTimezone`) and silently falls back to the default.
|
|
548
597
|
|
|
549
|
-
Plain `YYYY-MM-DD` filter values are expanded into a `$gte`/`$lt` range spanning that local day; values with an explicit offset (`Z`, `+06:00`) are treated as absolute instants and passed through as-is.
|
|
598
|
+
Plain `YYYY-MM-DD` filter values are expanded into a `$gte`/`$lt` range spanning that local day; values with an explicit offset (`Z`, `+06:00`) are treated as absolute instants and passed through as-is. Every custom range method below applies the same timezone-aware logic.
|
|
550
599
|
|
|
551
600
|
## Builder Methods
|
|
552
601
|
|
|
553
602
|
All builder methods return `this` and are fully chainable. Recommended call order:
|
|
554
603
|
|
|
555
604
|
```
|
|
556
|
-
allowFields → dateFields → where → range → filter → globalSearch → sort → project → lookup/addStage → paginate
|
|
605
|
+
allowFields → dateFields/objectIdFields → where → range/rangeXxx → filter → globalSearch → sort → project → lookup/addStage/computeField → paginate/paginateCursor/count/distinct/stats/stream
|
|
557
606
|
```
|
|
558
607
|
|
|
559
608
|
---
|
|
@@ -578,13 +627,23 @@ Explicit list of fields treated as dates for timezone-aware coercion. When omitt
|
|
|
578
627
|
|
|
579
628
|
---
|
|
580
629
|
|
|
630
|
+
### `.objectIdFields(fields: string[])`
|
|
631
|
+
|
|
632
|
+
Explicit list of fields treated as ObjectId references, so a client-supplied 24-char hex string (`?categoryId=...`) is coerced to `Types.ObjectId` instead of being compared as a plain string (which would never match, since it's a different BSON type). When omitted, falls back to a name heuristic matching `_id` or any field ending in `Id` (e.g. `categoryId`, `basicInfo.brandId`).
|
|
633
|
+
|
|
634
|
+
```ts
|
|
635
|
+
.objectIdFields(['branchId', 'categoryId'])
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
---
|
|
639
|
+
|
|
581
640
|
### `.filter()`
|
|
582
641
|
|
|
583
642
|
Parses `req.query` into the aggregation `$match` stage's client-derived portion. Runs, in order:
|
|
584
643
|
|
|
585
644
|
1. Strips reserved keys (`page`, `sort`, `limit`, `fields`, `q`)
|
|
586
645
|
2. `sanitize()` — recursively drops non-plain values (class instances, functions), capped at nesting depth 5
|
|
587
|
-
3. `coerceAll()` — timezone-aware date coercion + boolean coercion + operator-name coercion (`gt` → `$gt`, etc.)
|
|
646
|
+
3. `coerceAll()` — timezone-aware date coercion + ObjectId coercion + boolean coercion + numeric coercion + operator-name coercion (`gt` → `$gt`, etc.)
|
|
588
647
|
4. `enforceAllowlist()` — strips any non-operator key not in `.allowFields()`
|
|
589
648
|
5. `rejectDisallowedOperators()` — throws `QueryAggregateValidationError` on `$where`, `$expr`, `$function`, `$accumulator`, `$map`, `$reduce`, `$filter`, or any unexpected top-level `$` operator
|
|
590
649
|
|
|
@@ -623,6 +682,95 @@ Adds a hard, server-defined UTC date range on `field`, computed in this instance
|
|
|
623
682
|
|
|
624
683
|
---
|
|
625
684
|
|
|
685
|
+
## Custom Range Methods
|
|
686
|
+
|
|
687
|
+
Beyond the fixed `RangePreset` values above, six additional methods cover any custom day, span, rolling window, or hour-based filter — without touching `.range()`'s own logic. All of them behave exactly like `.range()`: they write a hard, non-client-overridable condition into `_serverConditions`, in this instance's timezone, and throw `QueryAggregateValidationError` on bad input.
|
|
688
|
+
|
|
689
|
+
> ⚠️ Only call **one** range method per field. If you call two on the same field (e.g. `.range()` then `.rangeCustom()` on `createdAt`), the later call simply overwrites the earlier one.
|
|
690
|
+
|
|
691
|
+
### `.rangeCustomDay(field: string, date: string)`
|
|
692
|
+
|
|
693
|
+
A single arbitrary local calendar date (`YYYY-MM-DD`) — for "show me everything from this specific day" rather than a relative preset.
|
|
694
|
+
|
|
695
|
+
```ts
|
|
696
|
+
.rangeCustomDay('createdAt', '2026-03-14')
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
### `.rangeBetween(field: string, custom: CustomDateRangeInput)`
|
|
700
|
+
|
|
701
|
+
An arbitrary inclusive local-date span — the classic "from / to" date-picker filter.
|
|
702
|
+
|
|
703
|
+
```ts
|
|
704
|
+
.rangeBetween('createdAt', { from: '2026-01-01', to: '2026-01-31' })
|
|
705
|
+
```
|
|
706
|
+
|
|
707
|
+
### `.rangeLastNDays(field: string, days: number)`
|
|
708
|
+
|
|
709
|
+
A rolling window of the last N whole calendar days, inclusive of today — a parametrized version of the built-in `last7Days`/`last30Days` presets.
|
|
710
|
+
|
|
711
|
+
```ts
|
|
712
|
+
.rangeLastNDays('createdAt', 14) // last 14 calendar days
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
### `.rangeLastNHours(field: string, hours: number)`
|
|
716
|
+
|
|
717
|
+
A rolling window of the last N hours, ending at the exact moment the query runs. Unlike the day-based methods, this uses raw UTC instants with no calendar-day snapping — ideal for "recent activity" widgets.
|
|
718
|
+
|
|
719
|
+
```ts
|
|
720
|
+
.rangeLastNHours('createdAt', 6) // activity in the last 6 hours
|
|
721
|
+
```
|
|
722
|
+
|
|
723
|
+
### `.rangeHours(field: string, custom: CustomHourRangeInput)`
|
|
724
|
+
|
|
725
|
+
An explicit hour-of-day window on a specific local date — e.g. filtering orders placed during business hours.
|
|
726
|
+
|
|
727
|
+
```ts
|
|
728
|
+
.rangeHours('createdAt', { date: '2026-03-14', fromHour: 9, toHour: 17 })
|
|
729
|
+
// toHour is exclusive; pass 24 for "through end of day"
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
### `.rangeCustom(field: string, custom: CustomDateTimeRangeInput)`
|
|
733
|
+
|
|
734
|
+
The most flexible option — an explicit absolute datetime window. Each of `from`/`to` accepts:
|
|
735
|
+
|
|
736
|
+
- `"YYYY-MM-DD"` → local midnight in this instance's timezone
|
|
737
|
+
- `"YYYY-MM-DDTHH:mm:ss[.sss]"` → local wall-clock time in this instance's timezone
|
|
738
|
+
- an offset-bearing ISO string (`...Z`, `...+06:00`) → treated as an absolute instant
|
|
739
|
+
|
|
740
|
+
```ts
|
|
741
|
+
.rangeCustom('createdAt', {
|
|
742
|
+
from: '2026-03-14T09:30:00', // local wall-clock
|
|
743
|
+
to: '2026-03-14T18:45:00',
|
|
744
|
+
})
|
|
745
|
+
|
|
746
|
+
// or mixed with an explicit UTC instant:
|
|
747
|
+
.rangeCustom('createdAt', { from: '2026-03-14T00:00:00Z', to: '2026-03-15T00:00:00Z' })
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
---
|
|
751
|
+
|
|
752
|
+
### `.excludeSoftDeleted(field = 'deletedAt')`
|
|
753
|
+
|
|
754
|
+
Convenience server-side condition excluding soft-deleted documents. Matches both `null` and a genuinely missing field, per MongoDB's equality semantics. Not client-overridable.
|
|
755
|
+
|
|
756
|
+
```ts
|
|
757
|
+
.excludeSoftDeleted() // defaults to 'deletedAt'
|
|
758
|
+
.excludeSoftDeleted('removedAt') // or a custom field name
|
|
759
|
+
```
|
|
760
|
+
|
|
761
|
+
---
|
|
762
|
+
|
|
763
|
+
### `.whereIf(condition, conditions)`
|
|
764
|
+
|
|
765
|
+
Applies `.where(conditions)` only when `condition` is truthy — avoids scattering `if` statements around a chained builder call.
|
|
766
|
+
|
|
767
|
+
```ts
|
|
768
|
+
.whereIf(req.query.vip === 'true', { tier: 'vip' })
|
|
769
|
+
.whereIf(req.self.role !== 'admin', { branchId: req.self.linkedTo })
|
|
770
|
+
```
|
|
771
|
+
|
|
772
|
+
---
|
|
773
|
+
|
|
626
774
|
### `.globalSearch(fields: string[])`
|
|
627
775
|
|
|
628
776
|
Identical behavior to `QueryFind`: case-insensitive `$or` regex search across the given fields when `?q=` is present (max 200 chars). Regex-escaped to prevent ReDoS. Fields are filtered against the allowlist first.
|
|
@@ -641,6 +789,8 @@ Parses `?sort=` (e.g. `-createdAt,name`), capped at 5 fields, dropping any field
|
|
|
641
789
|
.sort()
|
|
642
790
|
```
|
|
643
791
|
|
|
792
|
+
> `.paginateCursor()` (below) seeks on this same sort configuration, so call `.sort()` before it if you need a field other than the default `createdAt`.
|
|
793
|
+
|
|
644
794
|
---
|
|
645
795
|
|
|
646
796
|
### `.project(defaultProjection?: string | Record<string, 0 | 1>)`
|
|
@@ -663,14 +813,14 @@ Controls the `$project` stage. Accepts a space-separated string (`"name status -
|
|
|
663
813
|
|
|
664
814
|
Adds a `$lookup` (join) stage, optionally followed by `$unwind`.
|
|
665
815
|
|
|
666
|
-
| Field | Type | Description
|
|
667
|
-
| -------------- |
|
|
668
|
-
| `from` | `string`
|
|
669
|
-
| `as` | `string`
|
|
670
|
-
| `localField` | `string?`
|
|
671
|
-
| `foreignField` | `string?`
|
|
672
|
-
| `pipeline` | `PipelineStage[]?`
|
|
673
|
-
| `single` | `boolean?`
|
|
816
|
+
| Field | Type | Description |
|
|
817
|
+
| -------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
818
|
+
| `from` | `string` | Collection name (not the model name) to join against. |
|
|
819
|
+
| `as` | `string` | Output array field name. |
|
|
820
|
+
| `localField` | `string?` | Local join field. |
|
|
821
|
+
| `foreignField` | `string?` | Foreign join field. |
|
|
822
|
+
| `pipeline` | `PipelineStage[]?` | Sub-pipeline form of `$lookup`, for complex/correlated joins. Cannot contain `$out`/`$merge`. |
|
|
823
|
+
| `single` | `boolean?` | When `true`, `$unwind`s the joined array (`preserveNullAndEmptyArrays: true`) so `as` becomes a single object instead of an array. |
|
|
674
824
|
|
|
675
825
|
```ts
|
|
676
826
|
.lookup({
|
|
@@ -684,6 +834,17 @@ Adds a `$lookup` (join) stage, optionally followed by `$unwind`.
|
|
|
684
834
|
|
|
685
835
|
---
|
|
686
836
|
|
|
837
|
+
### `.computeField(name: string, expression: unknown)`
|
|
838
|
+
|
|
839
|
+
Convenience wrapper over `.addStage()` for a single computed `$addFields` entry.
|
|
840
|
+
|
|
841
|
+
```ts
|
|
842
|
+
.computeField('margin', { $subtract: ['$price', '$cost'] })
|
|
843
|
+
// equivalent to: .addStage({ $addFields: { margin: { $subtract: ['$price', '$cost'] } } })
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
---
|
|
847
|
+
|
|
687
848
|
### `.addStage(stage: PipelineStage)`
|
|
688
849
|
|
|
689
850
|
Escape hatch for any other developer-authored stage: `$addFields`, `$group`, a post-join `$match`, a custom `$sort`, etc.
|
|
@@ -702,7 +863,7 @@ Escape hatch for any other developer-authored stage: `$addFields`, `$group`, a p
|
|
|
702
863
|
})
|
|
703
864
|
```
|
|
704
865
|
|
|
705
|
-
## Terminal
|
|
866
|
+
## Terminal & Utility Methods
|
|
706
867
|
|
|
707
868
|
### `.paginate(cachedTotal?: number)`
|
|
708
869
|
|
|
@@ -714,13 +875,136 @@ Executes the pipeline and returns `Promise<PaginatedResult<T>>`.
|
|
|
714
875
|
- If the requested `page` exceeds `totalPages`, page `1` is returned automatically (with the real `total`/`totalPages` still reported).
|
|
715
876
|
- `onSlowQuery` (if configured) fires with `{ elapsedMs, pipeline, sort, page, limit }` when the query exceeds `slowQueryThresholdMS`.
|
|
716
877
|
|
|
717
|
-
> **Note:** `$facet` buffers both branches in memory per query. For very large collections with expensive pre-facet stages (heavy `$lookup`/`$group` before pagination), pass `cachedTotal` on subsequent pages, or run count
|
|
878
|
+
> **Note:** `$facet` buffers both branches in memory per query. For very large collections with expensive pre-facet stages (heavy `$lookup`/`$group` before pagination), pass `cachedTotal` on subsequent pages, use `.paginateCursor()` instead, or run `.count()`/data as two separate calls.
|
|
718
879
|
|
|
719
880
|
```ts
|
|
720
881
|
const page1 = await builder.paginate();
|
|
721
882
|
const page2 = await builder.paginate(page1.total); // skips re-counting
|
|
722
883
|
```
|
|
723
884
|
|
|
885
|
+
---
|
|
886
|
+
|
|
887
|
+
### `.paginateCursor(opts?: CursorPaginateOptions)`
|
|
888
|
+
|
|
889
|
+
Keyset ("seek") pagination — scales far better than `.paginate()`'s `$skip` on deep pages of large collections, at the cost of not supporting "jump to page N". Seeks on whatever field `.sort()` resolved to (falls back to `createdAt` if `.sort()` wasn't called), using `_id` as a stable tiebreaker.
|
|
890
|
+
|
|
891
|
+
```ts
|
|
892
|
+
interface CursorPaginateOptions {
|
|
893
|
+
cursor?: string; // opaque cursor from a previous page's nextCursor
|
|
894
|
+
limit?: number; // overrides ?limit=, still capped by maxLimit
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
interface CursorPaginatedResult<T> {
|
|
898
|
+
data: T[];
|
|
899
|
+
limit: number;
|
|
900
|
+
nextCursor: string | null; // pass this back in as `cursor` for the next page
|
|
901
|
+
hasNextPage: boolean;
|
|
902
|
+
}
|
|
903
|
+
```
|
|
904
|
+
|
|
905
|
+
```ts
|
|
906
|
+
const p1 = await builder.sort().paginateCursor({ limit: 20 });
|
|
907
|
+
const p2 = await builder.paginateCursor({ cursor: p1.nextCursor!, limit: 20 });
|
|
908
|
+
// hasNextPage: false / nextCursor: null means you've reached the end
|
|
909
|
+
```
|
|
910
|
+
|
|
911
|
+
Great fit for infinite-scroll feeds and large-export pagination; not a drop-in replacement where the UI needs page numbers.
|
|
912
|
+
|
|
913
|
+
---
|
|
914
|
+
|
|
915
|
+
### `.count()`
|
|
916
|
+
|
|
917
|
+
Returns just the matching document count — cheaper than `.paginate()` when you don't need the data page. Ignores `.project()`/`.sort()`.
|
|
918
|
+
|
|
919
|
+
```ts
|
|
920
|
+
const total = await builder.count();
|
|
921
|
+
```
|
|
922
|
+
|
|
923
|
+
---
|
|
924
|
+
|
|
925
|
+
### `.distinct(field: string)`
|
|
926
|
+
|
|
927
|
+
Returns the distinct values of `field` under the current `.filter()`/`.where()`/range conditions.
|
|
928
|
+
|
|
929
|
+
```ts
|
|
930
|
+
const statuses = await builder.distinct('status');
|
|
931
|
+
// e.g. ['PENDING', 'PAID', 'CANCELLED']
|
|
932
|
+
```
|
|
933
|
+
|
|
934
|
+
---
|
|
935
|
+
|
|
936
|
+
### `.stats(specs: StatSpec[])`
|
|
937
|
+
|
|
938
|
+
Computes one or more aggregate metrics — `sum`, `avg`, `min`, `max`, `count` — in a **single round trip**. Ideal for dashboard totals. Ignores `.project()`/`.sort()`/pagination.
|
|
939
|
+
|
|
940
|
+
```ts
|
|
941
|
+
interface StatSpec {
|
|
942
|
+
name: string;
|
|
943
|
+
op: 'sum' | 'avg' | 'min' | 'max' | 'count';
|
|
944
|
+
field?: string; // required for every op except 'count'
|
|
945
|
+
}
|
|
946
|
+
```
|
|
947
|
+
|
|
948
|
+
```ts
|
|
949
|
+
const totals = await builder.stats([
|
|
950
|
+
{ name: 'revenue', op: 'sum', field: 'total' },
|
|
951
|
+
{ name: 'avgOrder', op: 'avg', field: 'total' },
|
|
952
|
+
{ name: 'orders', op: 'count' },
|
|
953
|
+
]);
|
|
954
|
+
// { revenue: 48213, avgOrder: 62.1, orders: 776 }
|
|
955
|
+
```
|
|
956
|
+
|
|
957
|
+
---
|
|
958
|
+
|
|
959
|
+
### `.stream()`
|
|
960
|
+
|
|
961
|
+
Returns a Mongoose `AggregationCursor` — async-iterable, no buffering of the full result set in memory. Use for large exports (CSV generation, bulk processing).
|
|
962
|
+
|
|
963
|
+
```ts
|
|
964
|
+
for await (const doc of builder.stream()) {
|
|
965
|
+
csvWriter.write(doc);
|
|
966
|
+
}
|
|
967
|
+
```
|
|
968
|
+
|
|
969
|
+
Ignores `page`/`limit`; add your own `$limit` via `.addStage()` if you want a hard cap.
|
|
970
|
+
|
|
971
|
+
---
|
|
972
|
+
|
|
973
|
+
### `.explain(verbosity?)`
|
|
974
|
+
|
|
975
|
+
Runs the built pipeline through Mongoose's `.explain()` — for debugging slow queries and verifying index usage. `verbosity` is `'queryPlanner'` (default), `'executionStats'`, or `'allPlansExecution'`.
|
|
976
|
+
|
|
977
|
+
```ts
|
|
978
|
+
const plan = await builder.explain('executionStats');
|
|
979
|
+
```
|
|
980
|
+
|
|
981
|
+
> Development/ops tool only — never call this in a production request path.
|
|
982
|
+
|
|
983
|
+
---
|
|
984
|
+
|
|
985
|
+
### `.clone()`
|
|
986
|
+
|
|
987
|
+
Deep-copies the current builder state (filters, sort, projection, stages) into a new, independent `QueryAggregate` instance. Handy for branching one shared base query into e.g. both `.paginate()` and `.stats()` without rebuilding the filters twice.
|
|
988
|
+
|
|
989
|
+
```ts
|
|
990
|
+
const base = builder.filter().sort().project('name total createdAt');
|
|
991
|
+
|
|
992
|
+
const [page, totals] = await Promise.all([
|
|
993
|
+
base.clone().paginate(),
|
|
994
|
+
base.clone().stats([{ name: 'revenue', op: 'sum', field: 'total' }]),
|
|
995
|
+
]);
|
|
996
|
+
```
|
|
997
|
+
|
|
998
|
+
---
|
|
999
|
+
|
|
1000
|
+
### `.debugPipeline()`
|
|
1001
|
+
|
|
1002
|
+
Returns the fully-built pipeline (`PipelineStage[]`) without executing it — for logging, snapshot tests, or sanity-checking what will actually run.
|
|
1003
|
+
|
|
1004
|
+
```ts
|
|
1005
|
+
console.log(builder.debugPipeline());
|
|
1006
|
+
```
|
|
1007
|
+
|
|
724
1008
|
## Recipes
|
|
725
1009
|
|
|
726
1010
|
**Join + post-join filter + group + paginate:**
|
|
@@ -761,6 +1045,71 @@ const result = await new QueryAggregate(OrderModel, req.query, { timezone })
|
|
|
761
1045
|
.paginate();
|
|
762
1046
|
```
|
|
763
1047
|
|
|
1048
|
+
**Custom hour-of-day window (business hours report):**
|
|
1049
|
+
|
|
1050
|
+
```ts
|
|
1051
|
+
const result = await new QueryAggregate(OrderModel, req.query, { timezone })
|
|
1052
|
+
.allowFields(['status'])
|
|
1053
|
+
.where({ branchId: req.self.linkedTo })
|
|
1054
|
+
.rangeHours('createdAt', { date: req.query.day as string, fromHour: 9, toHour: 21 })
|
|
1055
|
+
.filter()
|
|
1056
|
+
.sort()
|
|
1057
|
+
.paginate();
|
|
1058
|
+
```
|
|
1059
|
+
|
|
1060
|
+
**Dashboard: page + totals in parallel, off one shared base:**
|
|
1061
|
+
|
|
1062
|
+
```ts
|
|
1063
|
+
const base = new QueryAggregate(OrderModel, req.query, { timezone })
|
|
1064
|
+
.allowFields(['status', 'branchId', 'createdAt', 'total'])
|
|
1065
|
+
.dateFields(['createdAt'])
|
|
1066
|
+
.where({ branchId: req.self.linkedTo })
|
|
1067
|
+
.excludeSoftDeleted()
|
|
1068
|
+
.filter()
|
|
1069
|
+
.sort()
|
|
1070
|
+
.project('status createdAt total');
|
|
1071
|
+
|
|
1072
|
+
const [page, totals] = await Promise.all([
|
|
1073
|
+
base.clone().paginate(),
|
|
1074
|
+
base.clone().stats([
|
|
1075
|
+
{ name: 'revenue', op: 'sum', field: 'total' },
|
|
1076
|
+
{ name: 'orders', op: 'count' },
|
|
1077
|
+
]),
|
|
1078
|
+
]);
|
|
1079
|
+
```
|
|
1080
|
+
|
|
1081
|
+
**Infinite scroll with keyset pagination:**
|
|
1082
|
+
|
|
1083
|
+
```ts
|
|
1084
|
+
const builder = new QueryAggregate(PostModel, req.query, { timezone })
|
|
1085
|
+
.allowFields(['authorId', 'createdAt'])
|
|
1086
|
+
.where({ published: true })
|
|
1087
|
+
.filter()
|
|
1088
|
+
.sort();
|
|
1089
|
+
|
|
1090
|
+
const page = await builder.paginateCursor({
|
|
1091
|
+
cursor: req.query.cursor as string | undefined,
|
|
1092
|
+
limit: 20,
|
|
1093
|
+
});
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
**Streaming a large CSV export:**
|
|
1097
|
+
|
|
1098
|
+
```ts
|
|
1099
|
+
const builder = new QueryAggregate(OrderModel, req.query, { timezone })
|
|
1100
|
+
.allowFields(['status', 'createdAt'])
|
|
1101
|
+
.where({ branchId: req.self.linkedTo })
|
|
1102
|
+
.range('createdAt', 'thisMonth')
|
|
1103
|
+
.filter()
|
|
1104
|
+
.project('status createdAt total');
|
|
1105
|
+
|
|
1106
|
+
res.setHeader('Content-Type', 'text/csv');
|
|
1107
|
+
for await (const row of builder.stream()) {
|
|
1108
|
+
res.write(`${row.status},${row.createdAt.toISOString()},${row.total}\n`);
|
|
1109
|
+
}
|
|
1110
|
+
res.end();
|
|
1111
|
+
```
|
|
1112
|
+
|
|
764
1113
|
**Correlated sub-pipeline `$lookup` (needs `let`):**
|
|
765
1114
|
|
|
766
1115
|
The built-in `LookupOptions` type doesn't expose `let` for correlated sub-pipelines. For that case, drop to `.addStage()` directly:
|
|
@@ -784,39 +1133,43 @@ The built-in `LookupOptions` type doesn't expose `let` for correlated sub-pipeli
|
|
|
784
1133
|
The final pipeline is always assembled in this fixed order:
|
|
785
1134
|
|
|
786
1135
|
```
|
|
787
|
-
$match (from .where() + .filter() + .range() + .globalSearch(), merged via $and)
|
|
1136
|
+
$match (from .where() + .filter() + .range()/rangeXxx() + .globalSearch(), merged via $and)
|
|
788
1137
|
↓
|
|
789
|
-
[.lookup() / .addStage() calls, in the order you called them]
|
|
1138
|
+
[.lookup() / .addStage() / .computeField() calls, in the order you called them]
|
|
790
1139
|
↓
|
|
791
1140
|
$project (from .project(), if set)
|
|
792
1141
|
↓
|
|
793
1142
|
$sort (from .sort())
|
|
794
1143
|
↓
|
|
795
|
-
[
|
|
1144
|
+
[terminal stage: $skip/$limit, $facet, keyset $match + $limit, or $count/$group — added internally by the method you call]
|
|
796
1145
|
```
|
|
797
1146
|
|
|
798
1147
|
Implications:
|
|
799
1148
|
|
|
800
|
-
- Anything added via `.addStage()` runs **after** the base filter match and **before** projection/sort.
|
|
1149
|
+
- Anything added via `.addStage()`/`.computeField()` runs **after** the base filter match and **before** projection/sort.
|
|
801
1150
|
- If you `$group`/reshape documents, do it before `.project()` — or skip `.project()` and use `.addStage({ $project: {...} })` for full control over the new shape.
|
|
802
1151
|
- If you add your own `$sort` via `.addStage()` _and_ also call `.sort()`, both stages are included (the builder's `.sort()` stage is always appended last in the base pipeline) — harmless but redundant. Prefer one or the other.
|
|
1152
|
+
- `.count()`, `.distinct()`, and `.stats()` intentionally skip `$project`/`$sort` — they only need `$match` + your `.lookup()`/`.addStage()` stages before their own terminal `$count`/`$group`.
|
|
1153
|
+
- `.paginateCursor()` builds its own `$match`/`$sort`/`$limit` tail (the keyset condition), separate from `.paginate()`'s `$facet` tail.
|
|
803
1154
|
|
|
804
1155
|
## Security
|
|
805
1156
|
|
|
806
|
-
| Protection | Detail
|
|
807
|
-
|
|
|
808
|
-
| **NoSQL injection**
|
|
809
|
-
| **Banned operators**
|
|
810
|
-
| **Destructive stages**
|
|
811
|
-
| **ReDoS**
|
|
812
|
-
| **Oversized search**
|
|
813
|
-
| **Deep nesting DoS**
|
|
814
|
-
| **Page size DoS**
|
|
815
|
-
| **Sort abuse**
|
|
816
|
-
| **Runaway queries**
|
|
817
|
-
| **Bad timezone input**
|
|
818
|
-
| **
|
|
819
|
-
| **
|
|
1157
|
+
| Protection | Detail |
|
|
1158
|
+
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
1159
|
+
| **NoSQL injection** | Allowlist enforced on `.filter()`/`.sort()`/`.project()` via `.allowFields()` |
|
|
1160
|
+
| **Banned operators** | `$where`, `$expr`, `$function`, `$accumulator`, `$map`, `$reduce`, `$filter` rejected recursively, any depth, in client input |
|
|
1161
|
+
| **Destructive stages** | `$out` / `$merge` rejected in `.addStage()` / `.lookup()` sub-pipelines |
|
|
1162
|
+
| **ReDoS** | `.globalSearch()` terms are regex-escaped before compilation |
|
|
1163
|
+
| **Oversized search** | `?q=` capped at 200 characters |
|
|
1164
|
+
| **Deep nesting DoS** | Client filter object nesting capped at depth 5 (`sanitize()`) |
|
|
1165
|
+
| **Page size DoS** | `limit` hard-capped at `maxLimit` (default 100), including in `.paginateCursor()` |
|
|
1166
|
+
| **Sort abuse** | Sort fields hard-capped at 5 |
|
|
1167
|
+
| **Runaway queries** | `maxTimeMS` applied to the aggregation; `onSlowQuery` for observability |
|
|
1168
|
+
| **Bad timezone input** | Invalid IANA zone validated once at construction, falls back to default, never throws mid-query |
|
|
1169
|
+
| **Bad custom-range input** | `rangeCustomDay`/`rangeBetween`/`rangeLastNDays`/`rangeLastNHours`/`rangeHours`/`rangeCustom` all throw `QueryAggregateValidationError` on malformed dates, non-positive counts, or invalid hour bounds — never silently produce a wrong range |
|
|
1170
|
+
| **Server condition override** | `.where()` / `.range()` / every custom range method are merged last via `$and` — URL params can never override them |
|
|
1171
|
+
| **Tampered cursors** | `.paginateCursor()` cursors are opaque base64url-encoded JSON; a malformed cursor throws `QueryAggregateValidationError` rather than silently misbehaving |
|
|
1172
|
+
| **Untrusted `.addStage()` input** | Not sanitized/allowlisted by design — documented as a trusted, developer-authored-only escape hatch |
|
|
820
1173
|
|
|
821
1174
|
> **Important:** `.addStage()` and the `pipeline` option in `.lookup()` are for **server-defined stages only**. They skip the sanitizer/allowlist/operator-rejection that protects `.filter()`/`.where()`. Never interpolate raw `req.query`/`req.body` values into an `.addStage()` call without validating them yourself first.
|
|
822
1175
|
|
|
@@ -833,6 +1186,13 @@ import {
|
|
|
833
1186
|
SlowQueryInfo,
|
|
834
1187
|
QueryParams,
|
|
835
1188
|
PaginatedResult,
|
|
1189
|
+
CustomDayInput,
|
|
1190
|
+
CustomDateRangeInput,
|
|
1191
|
+
CustomHourRangeInput,
|
|
1192
|
+
CustomDateTimeRangeInput,
|
|
1193
|
+
CursorPaginateOptions,
|
|
1194
|
+
CursorPaginatedResult,
|
|
1195
|
+
StatSpec,
|
|
836
1196
|
} from 'mongoose-query-find';
|
|
837
1197
|
```
|
|
838
1198
|
|
|
@@ -872,4 +1232,44 @@ interface SlowQueryInfo {
|
|
|
872
1232
|
page: number;
|
|
873
1233
|
limit: number;
|
|
874
1234
|
}
|
|
1235
|
+
|
|
1236
|
+
// ── Custom range types ──────────────────────────────────────────────────────
|
|
1237
|
+
|
|
1238
|
+
type CustomDayInput = string; // "YYYY-MM-DD"
|
|
1239
|
+
|
|
1240
|
+
interface CustomDateRangeInput {
|
|
1241
|
+
from: string; // "YYYY-MM-DD"
|
|
1242
|
+
to: string; // "YYYY-MM-DD"
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
interface CustomHourRangeInput {
|
|
1246
|
+
date: string; // "YYYY-MM-DD"
|
|
1247
|
+
fromHour: number; // 0–24
|
|
1248
|
+
toHour: number; // 0–24, exclusive, must be > fromHour
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
interface CustomDateTimeRangeInput {
|
|
1252
|
+
from: string; // "YYYY-MM-DD" | "YYYY-MM-DDTHH:mm:ss[.sss]" | offset-bearing ISO string
|
|
1253
|
+
to: string;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// ── Advanced-feature types ──────────────────────────────────────────────────
|
|
1257
|
+
|
|
1258
|
+
interface CursorPaginateOptions {
|
|
1259
|
+
cursor?: string;
|
|
1260
|
+
limit?: number;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
interface CursorPaginatedResult<T> {
|
|
1264
|
+
data: T[];
|
|
1265
|
+
limit: number;
|
|
1266
|
+
nextCursor: string | null;
|
|
1267
|
+
hasNextPage: boolean;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
interface StatSpec {
|
|
1271
|
+
name: string;
|
|
1272
|
+
op: 'sum' | 'avg' | 'min' | 'max' | 'count';
|
|
1273
|
+
field?: string;
|
|
1274
|
+
}
|
|
875
1275
|
```
|