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/dist/aggregate.d.ts
CHANGED
|
@@ -43,6 +43,23 @@
|
|
|
43
43
|
* stages — it only blocks destructive stage types ($out/$merge). It does NOT
|
|
44
44
|
* run the client-input sanitizer; that only applies to .filter()/.where(),
|
|
45
45
|
* which parse untrusted req.query / req.body values.
|
|
46
|
+
*
|
|
47
|
+
* ── Custom ranges ────────────────────────────────────────────────────────────
|
|
48
|
+
* `.range(field, preset)` covers the fixed RangePreset values (today,
|
|
49
|
+
* yesterday, last7Days, last30Days, thisWeek, thisMonth). For anything more
|
|
50
|
+
* specific — a single arbitrary day, an arbitrary date span, a rolling
|
|
51
|
+
* window of N days/hours, an explicit hour-of-day window, or an explicit
|
|
52
|
+
* absolute datetime window — use the new custom range methods below:
|
|
53
|
+
*
|
|
54
|
+
* .rangeCustomDay(field, '2026-03-14')
|
|
55
|
+
* .rangeBetween(field, { from: '2026-01-01', to: '2026-01-31' })
|
|
56
|
+
* .rangeLastNDays(field, 14)
|
|
57
|
+
* .rangeLastNHours(field, 6)
|
|
58
|
+
* .rangeHours(field, { date: '2026-03-14', fromHour: 9, toHour: 17 })
|
|
59
|
+
* .rangeCustom(field, { from: '2026-03-14T09:00:00', to: '2026-03-15T00:00:00' })
|
|
60
|
+
*
|
|
61
|
+
* All of these behave like .range(): they set a hard, server-side condition
|
|
62
|
+
* that the client cannot override via query params.
|
|
46
63
|
*/
|
|
47
64
|
import { Model, PipelineStage } from 'mongoose';
|
|
48
65
|
export interface QueryParams {
|
|
@@ -70,6 +87,50 @@ export interface SlowQueryInfo {
|
|
|
70
87
|
limit: number;
|
|
71
88
|
}
|
|
72
89
|
export type RangePreset = 'today' | 'yesterday' | 'last7Days' | 'last30Days' | 'thisWeek' | 'thisMonth';
|
|
90
|
+
/** A single arbitrary local calendar date, e.g. "2026-03-14". */
|
|
91
|
+
export type CustomDayInput = string;
|
|
92
|
+
/** An inclusive local-date span, e.g. { from: '2026-01-01', to: '2026-01-31' }. */
|
|
93
|
+
export interface CustomDateRangeInput {
|
|
94
|
+
from: string;
|
|
95
|
+
to: string;
|
|
96
|
+
}
|
|
97
|
+
/** An explicit hour-of-day window on a given local date (0–24, `toHour` exclusive; pass 24 for "through end of day"). */
|
|
98
|
+
export interface CustomHourRangeInput {
|
|
99
|
+
date: string;
|
|
100
|
+
fromHour: number;
|
|
101
|
+
toHour: number;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* An explicit absolute datetime window. Each of `from`/`to` accepts:
|
|
105
|
+
* - "YYYY-MM-DD" -> local midnight in this instance's timezone
|
|
106
|
+
* - "YYYY-MM-DDTHH:mm:ss[.sss]" -> local wall-clock time in this instance's timezone
|
|
107
|
+
* - an offset-bearing ISO string ("...Z" / "...+06:00") -> absolute instant
|
|
108
|
+
*/
|
|
109
|
+
export interface CustomDateTimeRangeInput {
|
|
110
|
+
from: string;
|
|
111
|
+
to: string;
|
|
112
|
+
}
|
|
113
|
+
/** Options for .paginateCursor() — keyset/seek pagination, better than skip/limit on large collections. */
|
|
114
|
+
export interface CursorPaginateOptions {
|
|
115
|
+
/** Opaque cursor from a previous page's `nextCursor`. Omit for the first page. */
|
|
116
|
+
cursor?: string;
|
|
117
|
+
/** Overrides the instance's parsed ?limit=, capped by maxLimit like normal pagination. */
|
|
118
|
+
limit?: number;
|
|
119
|
+
}
|
|
120
|
+
export interface CursorPaginatedResult<T> {
|
|
121
|
+
data: T[];
|
|
122
|
+
limit: number;
|
|
123
|
+
/** Pass this back as `cursor` to fetch the next page; null when there are no more results. */
|
|
124
|
+
nextCursor: string | null;
|
|
125
|
+
hasNextPage: boolean;
|
|
126
|
+
}
|
|
127
|
+
/** One aggregate metric for .stats() — e.g. { name: 'revenue', op: 'sum', field: 'total' }. */
|
|
128
|
+
export interface StatSpec {
|
|
129
|
+
name: string;
|
|
130
|
+
op: 'sum' | 'avg' | 'min' | 'max' | 'count';
|
|
131
|
+
/** Required for every op except 'count'. */
|
|
132
|
+
field?: string;
|
|
133
|
+
}
|
|
73
134
|
export interface LookupOptions {
|
|
74
135
|
/** Collection name (not the model name) to join against. */
|
|
75
136
|
from: string;
|
|
@@ -114,6 +175,7 @@ export declare class QueryAggregate<T> {
|
|
|
114
175
|
private _allowedLookup;
|
|
115
176
|
private _canonicalMap;
|
|
116
177
|
private _dateFieldsLookup;
|
|
178
|
+
private _objectIdFieldsLookup;
|
|
117
179
|
/** URL-derived filter and server conditions are kept separate so server
|
|
118
180
|
* conditions (merged last) can never be overridden by URL params. */
|
|
119
181
|
private _urlFilter;
|
|
@@ -133,12 +195,31 @@ export declare class QueryAggregate<T> {
|
|
|
133
195
|
allowFields(fields: string[]): this;
|
|
134
196
|
/** Explicit list of fields treated as dates for timezone-aware coercion. Falls back to a name heuristic (createdAt/updatedAt/...) when omitted. */
|
|
135
197
|
dateFields(fields: string[]): this;
|
|
198
|
+
/** Explicit list of fields treated as ObjectId refs for coercion (client-supplied hex strings -> Types.ObjectId). Falls back to a name heuristic (_id/*Id) when omitted. */
|
|
199
|
+
objectIdFields(fields: string[]): this;
|
|
136
200
|
/** Parses URL query params (req.query) into a Mongoose filter. Only allowlisted fields pass through. */
|
|
137
201
|
filter(): this;
|
|
138
202
|
/** Mandatory server-side conditions the client cannot override — merged into the final $match last. */
|
|
139
203
|
where(conditions: Partial<Record<keyof T, unknown>>): this;
|
|
140
204
|
/** Adds a hard, server-defined UTC date range (in this instance's timezone) on `field`. Not client-overridable. */
|
|
141
205
|
range(field: string, preset: RangePreset): this;
|
|
206
|
+
/** Hard server-side condition for a single arbitrary local calendar date (e.g. "2026-03-14"), in this instance's timezone. Not client-overridable. */
|
|
207
|
+
rangeCustomDay(field: string, date: CustomDayInput): this;
|
|
208
|
+
/** Hard server-side condition for an arbitrary inclusive local-date span (e.g. { from: "2026-01-01", to: "2026-01-31" }), in this instance's timezone. Not client-overridable. */
|
|
209
|
+
rangeBetween(field: string, custom: CustomDateRangeInput): this;
|
|
210
|
+
/** Hard server-side condition for a rolling window of the last N whole calendar days (inclusive of today), in this instance's timezone. Not client-overridable. */
|
|
211
|
+
rangeLastNDays(field: string, days: number): this;
|
|
212
|
+
/** Hard server-side condition for a rolling window of the last N hours, ending at the moment this is called (exact UTC instants — no calendar-date snapping). Not client-overridable. */
|
|
213
|
+
rangeLastNHours(field: string, hours: number): this;
|
|
214
|
+
/** Hard server-side condition for an explicit hour-of-day window on a given local date (e.g. 09:00–17:00 on "2026-03-14"), in this instance's timezone. `toHour` is exclusive; pass 24 for "through end of day". Not client-overridable. */
|
|
215
|
+
rangeHours(field: string, custom: CustomHourRangeInput): this;
|
|
216
|
+
/**
|
|
217
|
+
* Hard server-side condition for an explicit absolute datetime window.
|
|
218
|
+
* Accepts "YYYY-MM-DD" (local midnight), "YYYY-MM-DDTHH:mm:ss" (local
|
|
219
|
+
* wall-clock), or an offset-bearing ISO string (absolute instant) for
|
|
220
|
+
* both `from` and `to`. Not client-overridable.
|
|
221
|
+
*/
|
|
222
|
+
rangeCustom(field: string, custom: CustomDateTimeRangeInput): this;
|
|
142
223
|
/** Case-insensitive full-text search across the given fields when ?q= is present. */
|
|
143
224
|
globalSearch(fields: string[]): this;
|
|
144
225
|
/** Parses ?sort= (e.g. "-createdAt,name"). Fields not in allowFields() are dropped; falls back to DEFAULT_SORT. */
|
|
@@ -158,6 +239,12 @@ export declare class QueryAggregate<T> {
|
|
|
158
239
|
/** [start of fromStr, start of (toStr + 1 day)) in this instance's timezone — an inclusive local-date range. */
|
|
159
240
|
private utcRangeForLocalDates;
|
|
160
241
|
private buildMatchStage;
|
|
242
|
+
/** Match + lookups/custom stages only, no $project/$sort — shared by count()/distinct()/stats(), which don't need either. */
|
|
243
|
+
private buildMatchAndStagesPipeline;
|
|
244
|
+
/** Encodes a keyset cursor from a result row: the current sort field's value plus `_id` as a stable tiebreaker. */
|
|
245
|
+
private encodeCursor;
|
|
246
|
+
/** Decodes a cursor produced by encodeCursor(), restoring Date/ObjectId typing so comparisons stay type-correct. */
|
|
247
|
+
private decodeCursor;
|
|
161
248
|
/** Base pipeline shared by every execution path: match -> lookups/custom stages -> project -> sort. */
|
|
162
249
|
private buildBasePipeline;
|
|
163
250
|
private execAggregate;
|
|
@@ -172,6 +259,49 @@ export declare class QueryAggregate<T> {
|
|
|
172
259
|
* `cachedTotal` on subsequent pages, or run count/data as two calls.
|
|
173
260
|
*/
|
|
174
261
|
paginate(cachedTotal?: number): Promise<PaginatedResult<T>>;
|
|
262
|
+
/** Returns just the matching document count — cheaper than paginate() when you don't need the data page. Ignores $project/$sort. */
|
|
263
|
+
count(): Promise<number>;
|
|
264
|
+
/** Returns the distinct values of `field` for the current filter/where/range conditions. */
|
|
265
|
+
distinct<V = unknown>(field: string): Promise<V[]>;
|
|
266
|
+
/**
|
|
267
|
+
* Computes one or more aggregate metrics (sum/avg/min/max/count) over the
|
|
268
|
+
* current filter/where/range conditions in a single round trip — handy for
|
|
269
|
+
* dashboard totals ("revenue", "avgOrderValue", "orderCount", ...).
|
|
270
|
+
* Ignores $project/$sort/pagination.
|
|
271
|
+
*/
|
|
272
|
+
stats(specs: StatSpec[]): Promise<Record<string, number>>;
|
|
273
|
+
/**
|
|
274
|
+
* Streams results as an async-iterable cursor instead of buffering the
|
|
275
|
+
* whole page in memory — use for large exports (CSV generation, bulk
|
|
276
|
+
* processing) with `for await (const doc of qa.stream())`. Ignores
|
|
277
|
+
* page/limit; add your own $limit via .addStage() if you want a cap.
|
|
278
|
+
*/
|
|
279
|
+
stream(): ReturnType<ReturnType<Model<T>['aggregate']>['cursor']>;
|
|
280
|
+
/**
|
|
281
|
+
* Keyset ("seek") pagination — scales far better than .paginate()'s
|
|
282
|
+
* $skip on deep pages of large collections, at the cost of not supporting
|
|
283
|
+
* "jump to page N". Requires .sort() to have been called with exactly the
|
|
284
|
+
* field you want to seek on (falls back to DEFAULT_SORT's `createdAt`
|
|
285
|
+
* otherwise). Pass the previous page's `nextCursor` back in as `cursor`
|
|
286
|
+
* to continue; a `hasNextPage: false` / `nextCursor: null` page is the end.
|
|
287
|
+
*/
|
|
288
|
+
paginateCursor(opts?: CursorPaginateOptions): Promise<CursorPaginatedResult<T>>;
|
|
289
|
+
/**
|
|
290
|
+
* Runs the built pipeline through Mongoose's .explain() for debugging
|
|
291
|
+
* slow queries / verifying index usage. Never use in a hot request path —
|
|
292
|
+
* this is a development/ops tool.
|
|
293
|
+
*/
|
|
294
|
+
explain(verbosity?: 'queryPlanner' | 'executionStats' | 'allPlansExecution'): Promise<unknown>;
|
|
295
|
+
/** Convenience wrapper over addStage() for a computed $addFields entry, e.g. .computeField('margin', { $subtract: ['$price', '$cost'] }). */
|
|
296
|
+
computeField(name: string, expression: unknown): this;
|
|
297
|
+
/** Convenience server-side condition excluding soft-deleted docs (matches both `null` and a missing field, per MongoDB equality semantics). Not client-overridable. */
|
|
298
|
+
excludeSoftDeleted(field?: string): this;
|
|
299
|
+
/** Applies .where(conditions) only when `condition` is truthy — avoids scattering if-statements around chained builder calls. */
|
|
300
|
+
whereIf(condition: unknown, conditions: Partial<Record<keyof T, unknown>>): this;
|
|
301
|
+
/** Deep-copies the current builder state (filters, sort, projection, stages) into a new independent instance — handy for branching one shared base query into e.g. both .paginate() and .stats() without rebuilding it twice. */
|
|
302
|
+
clone(): QueryAggregate<T>;
|
|
303
|
+
/** Returns the fully-built pipeline without executing it — for logging, snapshot tests, or sanity-checking what will actually run. */
|
|
304
|
+
debugPipeline(): PipelineStage[];
|
|
175
305
|
}
|
|
176
306
|
export default QueryAggregate;
|
|
177
307
|
//# sourceMappingURL=aggregate.d.ts.map
|
package/dist/aggregate.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aggregate.d.ts","sourceRoot":"","sources":["../src/aggregate.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"aggregate.d.ts","sourceRoot":"","sources":["../src/aggregate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8DG;AAIH,OAAO,EAAmB,KAAK,EAAE,aAAa,EAAS,MAAM,UAAU,CAAC;AA6DxE,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,CAAC,CAAC,EAAE,MAAM,CAAC;IACX,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,IAAI,EAAE,CAAC,EAAE,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,OAAO,CAAC;IACrB,WAAW,EAAE,OAAO,CAAC;CACtB;AAED,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,WAAW,GACnB,OAAO,GACP,WAAW,GACX,WAAW,GACX,YAAY,GACZ,UAAU,GACV,WAAW,CAAC;AAKhB,iEAAiE;AACjE,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC;AAEpC,mFAAmF;AACnF,MAAM,WAAW,oBAAoB;I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C;IASjE;;;;;;;OAOG;IACG,cAAc,CAClB,IAAI,GAAE,qBAA0B,GAC/B,OAAO,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;IA4CpC;;;;OAIG;IACG,OAAO,CACX,SAAS,GACL,cAAc,GACd,gBAAgB,GAChB,mBAAoC,GACvC,OAAO,CAAC,OAAO,CAAC;IAKnB,6IAA6I;IAC7I,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,GAAG,IAAI;IAMrD,uKAAuK;IACvK,kBAAkB,CAAC,KAAK,SAAc,GAAG,IAAI;IAK7C,iIAAiI;IACjI,OAAO,CACL,SAAS,EAAE,OAAO,EAClB,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,GAC5C,IAAI;IAKP,iOAAiO;IACjO,KAAK,IAAI,cAAc,CAAC,CAAC,CAAC;IAsB1B,sIAAsI;IACtI,aAAa,IAAI,aAAa,EAAE;CAGjC;AAED,eAAe,cAAc,CAAC"}
|
package/dist/aggregate.js
CHANGED
|
@@ -44,11 +44,29 @@
|
|
|
44
44
|
* stages — it only blocks destructive stage types ($out/$merge). It does NOT
|
|
45
45
|
* run the client-input sanitizer; that only applies to .filter()/.where(),
|
|
46
46
|
* which parse untrusted req.query / req.body values.
|
|
47
|
+
*
|
|
48
|
+
* ── Custom ranges ────────────────────────────────────────────────────────────
|
|
49
|
+
* `.range(field, preset)` covers the fixed RangePreset values (today,
|
|
50
|
+
* yesterday, last7Days, last30Days, thisWeek, thisMonth). For anything more
|
|
51
|
+
* specific — a single arbitrary day, an arbitrary date span, a rolling
|
|
52
|
+
* window of N days/hours, an explicit hour-of-day window, or an explicit
|
|
53
|
+
* absolute datetime window — use the new custom range methods below:
|
|
54
|
+
*
|
|
55
|
+
* .rangeCustomDay(field, '2026-03-14')
|
|
56
|
+
* .rangeBetween(field, { from: '2026-01-01', to: '2026-01-31' })
|
|
57
|
+
* .rangeLastNDays(field, 14)
|
|
58
|
+
* .rangeLastNHours(field, 6)
|
|
59
|
+
* .rangeHours(field, { date: '2026-03-14', fromHour: 9, toHour: 17 })
|
|
60
|
+
* .rangeCustom(field, { from: '2026-03-14T09:00:00', to: '2026-03-15T00:00:00' })
|
|
61
|
+
*
|
|
62
|
+
* All of these behave like .range(): they set a hard, server-side condition
|
|
63
|
+
* that the client cannot override via query params.
|
|
47
64
|
*/
|
|
48
65
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
49
66
|
exports.QueryAggregate = exports.QueryAggregateValidationError = exports.QueryAggregateError = void 0;
|
|
50
67
|
const date_fns_1 = require("date-fns");
|
|
51
68
|
const date_fns_tz_1 = require("date-fns-tz");
|
|
69
|
+
const mongoose_1 = require("mongoose");
|
|
52
70
|
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
53
71
|
const RESERVED_KEYS = new Set(['page', 'sort', 'limit', 'fields', 'q']);
|
|
54
72
|
const DEFAULT_MAX_LIMIT = 100;
|
|
@@ -65,6 +83,14 @@ const PLAIN_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
|
65
83
|
// A string that already carries its own UTC offset ("Z" or "+06:00") is
|
|
66
84
|
// treated as an absolute instant rather than a local wall-clock time.
|
|
67
85
|
const HAS_OFFSET_RE = /([Zz]|[+-]\d{2}:?\d{2})$/;
|
|
86
|
+
// Matches only when the id-word is the LAST path segment (e.g. "_id",
|
|
87
|
+
// "categoryId", "basicInfo.brandId") — used as a fallback heuristic when
|
|
88
|
+
// .objectIdFields() isn't called explicitly. Mirrors DATE_FIELD_RE's approach.
|
|
89
|
+
const OBJECTID_FIELD_RE = /(^|\.)(_id|[a-zA-Z0-9]*Id)$/;
|
|
90
|
+
// A 24-char lowercase/uppercase hex string — the only shape isValidObjectId()
|
|
91
|
+
// should be trusted to interpret as "meant to be an ObjectId" rather than a
|
|
92
|
+
// 12-byte-length string that happens to also pass Mongoose's looser check.
|
|
93
|
+
const HEX24_RE = /^[a-fA-F0-9]{24}$/;
|
|
68
94
|
const COERCIBLE_OPS = new Set([
|
|
69
95
|
'eq',
|
|
70
96
|
'ne',
|
|
@@ -165,6 +191,18 @@ function isDateField(path, explicit) {
|
|
|
165
191
|
}
|
|
166
192
|
return DATE_FIELD_RE.test(path);
|
|
167
193
|
}
|
|
194
|
+
function isObjectIdField(path, explicit) {
|
|
195
|
+
if (!path)
|
|
196
|
+
return false;
|
|
197
|
+
const lc = path.toLowerCase();
|
|
198
|
+
if (explicit && explicit.size > 0) {
|
|
199
|
+
if (explicit.has(lc))
|
|
200
|
+
return true;
|
|
201
|
+
const lastSeg = lc.split('.').pop() ?? lc;
|
|
202
|
+
return explicit.has(lastSeg);
|
|
203
|
+
}
|
|
204
|
+
return OBJECTID_FIELD_RE.test(path);
|
|
205
|
+
}
|
|
168
206
|
// ─── Sanitization ─────────────────────────────────────────────────────────────
|
|
169
207
|
/** Recursively strips non-plain values (class instances, functions) from client input. */
|
|
170
208
|
function sanitize(value, depth = 0, path = '', onDrop) {
|
|
@@ -263,7 +301,7 @@ function enforceAllowlist(filter, allowedLookup, canonicalMap) {
|
|
|
263
301
|
return out;
|
|
264
302
|
}
|
|
265
303
|
// ─── Fused coercion pass (timezone-aware) ──────────────────────────────────────
|
|
266
|
-
function coerceAll(value, timezone, dateFieldsLookup, parentKey = '', parentOp) {
|
|
304
|
+
function coerceAll(value, timezone, dateFieldsLookup, objectIdFieldsLookup, parentKey = '', parentOp) {
|
|
267
305
|
if (value === null)
|
|
268
306
|
return null;
|
|
269
307
|
if (typeof value === 'string') {
|
|
@@ -281,6 +319,17 @@ function coerceAll(value, timezone, dateFieldsLookup, parentKey = '', parentOp)
|
|
|
281
319
|
}
|
|
282
320
|
return coerceDateScalar(value, timezone) ?? value;
|
|
283
321
|
}
|
|
322
|
+
// ObjectId coercion — applies to bare equality values ("?categoryId=...")
|
|
323
|
+
// as well as values nested under comparison/membership operators
|
|
324
|
+
// ("?categoryId[in]=...,..."), since a plain string never matches an
|
|
325
|
+
// ObjectId-typed field in MongoDB (different BSON types). Gated on the
|
|
326
|
+
// field heuristic/explicit list AND a strict 24-char hex shape so we
|
|
327
|
+
// never misinterpret a coincidentally-24-char plain string field.
|
|
328
|
+
if (isObjectIdField(parentKey, objectIdFieldsLookup) &&
|
|
329
|
+
HEX24_RE.test(value) &&
|
|
330
|
+
(0, mongoose_1.isValidObjectId)(value)) {
|
|
331
|
+
return new mongoose_1.Types.ObjectId(value);
|
|
332
|
+
}
|
|
284
333
|
// Numeric coercion for comparison/membership operators (eq/ne/gt/gte/lt/lte/in/nin).
|
|
285
334
|
// Without this, a string like "50" under { $lte: "50" } never matches a
|
|
286
335
|
// Number field in MongoDB, since comparison operators are type-sensitive.
|
|
@@ -297,7 +346,7 @@ function coerceAll(value, timezone, dateFieldsLookup, parentKey = '', parentOp)
|
|
|
297
346
|
if (Array.isArray(value)) {
|
|
298
347
|
const out = [];
|
|
299
348
|
for (let i = 0; i < value.length; i++) {
|
|
300
|
-
const coerced = coerceAll(value[i], timezone, dateFieldsLookup, parentKey, parentOp);
|
|
349
|
+
const coerced = coerceAll(value[i], timezone, dateFieldsLookup, objectIdFieldsLookup, parentKey, parentOp);
|
|
301
350
|
if (coerced !== undefined)
|
|
302
351
|
out.push(coerced);
|
|
303
352
|
}
|
|
@@ -311,7 +360,7 @@ function coerceAll(value, timezone, dateFieldsLookup, parentKey = '', parentOp)
|
|
|
311
360
|
const newKey = COERCIBLE_OPS.has(k) ? `$${k}` : k;
|
|
312
361
|
const isOp = k.startsWith('$') || COERCIBLE_OPS.has(k);
|
|
313
362
|
const childPath = isOp ? parentKey : parentKey ? `${parentKey}.${k}` : k;
|
|
314
|
-
out[newKey] = coerceAll(src[k], timezone, dateFieldsLookup, childPath, isOp ? k : undefined);
|
|
363
|
+
out[newKey] = coerceAll(src[k], timezone, dateFieldsLookup, objectIdFieldsLookup, childPath, isOp ? k : undefined);
|
|
315
364
|
}
|
|
316
365
|
return out;
|
|
317
366
|
}
|
|
@@ -355,7 +404,7 @@ function rejectBannedStages(stage) {
|
|
|
355
404
|
}
|
|
356
405
|
}
|
|
357
406
|
// ─── Filter builder ───────────────────────────────────────────────────────────
|
|
358
|
-
function buildFilter(raw, allowedLookup, canonicalMap, timezone, dateFieldsLookup, onDrop) {
|
|
407
|
+
function buildFilter(raw, allowedLookup, canonicalMap, timezone, dateFieldsLookup, objectIdFieldsLookup, onDrop) {
|
|
359
408
|
const stripped = {};
|
|
360
409
|
for (const k in raw) {
|
|
361
410
|
if (Object.prototype.hasOwnProperty.call(raw, k) && !RESERVED_KEYS.has(k)) {
|
|
@@ -363,7 +412,7 @@ function buildFilter(raw, allowedLookup, canonicalMap, timezone, dateFieldsLooku
|
|
|
363
412
|
}
|
|
364
413
|
}
|
|
365
414
|
const safe = sanitize(stripped, 0, '', onDrop);
|
|
366
|
-
const coerced = coerceAll(safe, timezone, dateFieldsLookup);
|
|
415
|
+
const coerced = coerceAll(safe, timezone, dateFieldsLookup, objectIdFieldsLookup);
|
|
367
416
|
const allowed = enforceAllowlist(coerced, allowedLookup, canonicalMap);
|
|
368
417
|
rejectDisallowedOperators(allowed);
|
|
369
418
|
return allowed;
|
|
@@ -435,6 +484,7 @@ class QueryAggregate {
|
|
|
435
484
|
this._allowedLookup = new Set();
|
|
436
485
|
this._canonicalMap = new Map();
|
|
437
486
|
this._dateFieldsLookup = null;
|
|
487
|
+
this._objectIdFieldsLookup = null;
|
|
438
488
|
/** URL-derived filter and server conditions are kept separate so server
|
|
439
489
|
* conditions (merged last) can never be overridden by URL params. */
|
|
440
490
|
this._urlFilter = {};
|
|
@@ -479,10 +529,15 @@ class QueryAggregate {
|
|
|
479
529
|
this._dateFieldsLookup = new Set(fields.map((f) => f.toLowerCase()));
|
|
480
530
|
return this;
|
|
481
531
|
}
|
|
532
|
+
/** Explicit list of fields treated as ObjectId refs for coercion (client-supplied hex strings -> Types.ObjectId). Falls back to a name heuristic (_id/*Id) when omitted. */
|
|
533
|
+
objectIdFields(fields) {
|
|
534
|
+
this._objectIdFieldsLookup = new Set(fields.map((f) => f.toLowerCase()));
|
|
535
|
+
return this;
|
|
536
|
+
}
|
|
482
537
|
// ── Builder methods ───────────────────────────────────────────────────────
|
|
483
538
|
/** Parses URL query params (req.query) into a Mongoose filter. Only allowlisted fields pass through. */
|
|
484
539
|
filter() {
|
|
485
|
-
const parsed = buildFilter(this.qs, this._allowedLookup, this._canonicalMap, this.options.timezone, this._dateFieldsLookup, this.options.onSanitizeDrop);
|
|
540
|
+
const parsed = buildFilter(this.qs, this._allowedLookup, this._canonicalMap, this.options.timezone, this._dateFieldsLookup, this._objectIdFieldsLookup, this.options.onSanitizeDrop);
|
|
486
541
|
Object.assign(this._urlFilter, parsed);
|
|
487
542
|
return this;
|
|
488
543
|
}
|
|
@@ -499,6 +554,95 @@ class QueryAggregate {
|
|
|
499
554
|
this._serverConditions[field] = { $gte: start, $lt: end };
|
|
500
555
|
return this;
|
|
501
556
|
}
|
|
557
|
+
// ── Custom range methods (additive — RangePreset/.range() above is
|
|
558
|
+
// untouched; these cover custom day / custom range / custom N-days /
|
|
559
|
+
// custom N-hours / custom hour-of-day window / custom absolute datetime
|
|
560
|
+
// window use cases) ─────────────────────────────────────────────────────
|
|
561
|
+
/** Hard server-side condition for a single arbitrary local calendar date (e.g. "2026-03-14"), in this instance's timezone. Not client-overridable. */
|
|
562
|
+
rangeCustomDay(field, date) {
|
|
563
|
+
if (!PLAIN_DATE_RE.test(date)) {
|
|
564
|
+
throw new QueryAggregateValidationError(`rangeCustomDay: "date" must be in YYYY-MM-DD format, got "${date}"`);
|
|
565
|
+
}
|
|
566
|
+
const { start, end } = this.utcRangeForLocalDates(date, date);
|
|
567
|
+
this._serverConditions[field] = { $gte: start, $lt: end };
|
|
568
|
+
return this;
|
|
569
|
+
}
|
|
570
|
+
/** Hard server-side condition for an arbitrary inclusive local-date span (e.g. { from: "2026-01-01", to: "2026-01-31" }), in this instance's timezone. Not client-overridable. */
|
|
571
|
+
rangeBetween(field, custom) {
|
|
572
|
+
const { from, to } = custom;
|
|
573
|
+
if (!PLAIN_DATE_RE.test(from) || !PLAIN_DATE_RE.test(to)) {
|
|
574
|
+
throw new QueryAggregateValidationError(`rangeBetween: "from"/"to" must be in YYYY-MM-DD format, got "${from}" / "${to}"`);
|
|
575
|
+
}
|
|
576
|
+
const { start, end } = this.utcRangeForLocalDates(from, to);
|
|
577
|
+
this._serverConditions[field] = { $gte: start, $lt: end };
|
|
578
|
+
return this;
|
|
579
|
+
}
|
|
580
|
+
/** Hard server-side condition for a rolling window of the last N whole calendar days (inclusive of today), in this instance's timezone. Not client-overridable. */
|
|
581
|
+
rangeLastNDays(field, days) {
|
|
582
|
+
if (!Number.isInteger(days) || days < 1) {
|
|
583
|
+
throw new QueryAggregateValidationError(`rangeLastNDays: "days" must be a positive integer, got ${days}`);
|
|
584
|
+
}
|
|
585
|
+
const tz = this.options.timezone;
|
|
586
|
+
const zonedNow = (0, date_fns_tz_1.toZonedTime)(new Date(), tz);
|
|
587
|
+
const todayStr = (0, date_fns_1.format)(zonedNow, 'yyyy-MM-dd');
|
|
588
|
+
const fromStr = shiftLocalDateString(todayStr, -(days - 1));
|
|
589
|
+
const { start, end } = this.utcRangeForLocalDates(fromStr, todayStr);
|
|
590
|
+
this._serverConditions[field] = { $gte: start, $lt: end };
|
|
591
|
+
return this;
|
|
592
|
+
}
|
|
593
|
+
/** Hard server-side condition for a rolling window of the last N hours, ending at the moment this is called (exact UTC instants — no calendar-date snapping). Not client-overridable. */
|
|
594
|
+
rangeLastNHours(field, hours) {
|
|
595
|
+
if (!Number.isInteger(hours) || hours < 1) {
|
|
596
|
+
throw new QueryAggregateValidationError(`rangeLastNHours: "hours" must be a positive integer, got ${hours}`);
|
|
597
|
+
}
|
|
598
|
+
const end = new Date();
|
|
599
|
+
const start = new Date(end.getTime() - hours * 60 * 60 * 1000);
|
|
600
|
+
this._serverConditions[field] = { $gte: start, $lt: end };
|
|
601
|
+
return this;
|
|
602
|
+
}
|
|
603
|
+
/** Hard server-side condition for an explicit hour-of-day window on a given local date (e.g. 09:00–17:00 on "2026-03-14"), in this instance's timezone. `toHour` is exclusive; pass 24 for "through end of day". Not client-overridable. */
|
|
604
|
+
rangeHours(field, custom) {
|
|
605
|
+
const { date, fromHour, toHour } = custom;
|
|
606
|
+
if (!PLAIN_DATE_RE.test(date)) {
|
|
607
|
+
throw new QueryAggregateValidationError(`rangeHours: "date" must be in YYYY-MM-DD format, got "${date}"`);
|
|
608
|
+
}
|
|
609
|
+
if (!Number.isInteger(fromHour) ||
|
|
610
|
+
!Number.isInteger(toHour) ||
|
|
611
|
+
fromHour < 0 ||
|
|
612
|
+
fromHour > 24 ||
|
|
613
|
+
toHour < 0 ||
|
|
614
|
+
toHour > 24 ||
|
|
615
|
+
toHour <= fromHour) {
|
|
616
|
+
throw new QueryAggregateValidationError(`rangeHours: "fromHour"/"toHour" must be integers 0–24 with toHour > fromHour, got ${fromHour} / ${toHour}`);
|
|
617
|
+
}
|
|
618
|
+
const tz = this.options.timezone;
|
|
619
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
620
|
+
const start = (0, date_fns_tz_1.fromZonedTime)(`${date}T${pad(fromHour)}:00:00.000`, tz);
|
|
621
|
+
const end = toHour === 24
|
|
622
|
+
? (0, date_fns_tz_1.fromZonedTime)(`${shiftLocalDateString(date, 1)}T00:00:00.000`, tz)
|
|
623
|
+
: (0, date_fns_tz_1.fromZonedTime)(`${date}T${pad(toHour)}:00:00.000`, tz);
|
|
624
|
+
this._serverConditions[field] = { $gte: start, $lt: end };
|
|
625
|
+
return this;
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Hard server-side condition for an explicit absolute datetime window.
|
|
629
|
+
* Accepts "YYYY-MM-DD" (local midnight), "YYYY-MM-DDTHH:mm:ss" (local
|
|
630
|
+
* wall-clock), or an offset-bearing ISO string (absolute instant) for
|
|
631
|
+
* both `from` and `to`. Not client-overridable.
|
|
632
|
+
*/
|
|
633
|
+
rangeCustom(field, custom) {
|
|
634
|
+
const tz = this.options.timezone;
|
|
635
|
+
const start = coerceDateScalar(custom.from, tz);
|
|
636
|
+
const end = coerceDateScalar(custom.to, tz);
|
|
637
|
+
if (!start || !end) {
|
|
638
|
+
throw new QueryAggregateValidationError(`rangeCustom: could not parse "from"/"to" — got "${custom.from}" / "${custom.to}"`);
|
|
639
|
+
}
|
|
640
|
+
if (end <= start) {
|
|
641
|
+
throw new QueryAggregateValidationError(`rangeCustom: "to" (${custom.to}) must be after "from" (${custom.from})`);
|
|
642
|
+
}
|
|
643
|
+
this._serverConditions[field] = { $gte: start, $lt: end };
|
|
644
|
+
return this;
|
|
645
|
+
}
|
|
502
646
|
/** Case-insensitive full-text search across the given fields when ?q= is present. */
|
|
503
647
|
globalSearch(fields) {
|
|
504
648
|
const raw = this.qs.q?.trim();
|
|
@@ -630,6 +774,50 @@ class QueryAggregate {
|
|
|
630
774
|
: base;
|
|
631
775
|
return Object.keys(finalFilter).length > 0 ? { $match: finalFilter } : null;
|
|
632
776
|
}
|
|
777
|
+
/** Match + lookups/custom stages only, no $project/$sort — shared by count()/distinct()/stats(), which don't need either. */
|
|
778
|
+
buildMatchAndStagesPipeline() {
|
|
779
|
+
const pipeline = [];
|
|
780
|
+
const matchStage = this.buildMatchStage();
|
|
781
|
+
if (matchStage)
|
|
782
|
+
pipeline.push(matchStage);
|
|
783
|
+
pipeline.push(...this._stages);
|
|
784
|
+
return pipeline;
|
|
785
|
+
}
|
|
786
|
+
/** Encodes a keyset cursor from a result row: the current sort field's value plus `_id` as a stable tiebreaker. */
|
|
787
|
+
encodeCursor(doc, sortField) {
|
|
788
|
+
const raw = doc[sortField];
|
|
789
|
+
let v = raw;
|
|
790
|
+
let t = 'other';
|
|
791
|
+
if (raw instanceof Date) {
|
|
792
|
+
v = raw.toISOString();
|
|
793
|
+
t = 'date';
|
|
794
|
+
}
|
|
795
|
+
else if (raw instanceof mongoose_1.Types.ObjectId) {
|
|
796
|
+
v = raw.toString();
|
|
797
|
+
t = 'objectid';
|
|
798
|
+
}
|
|
799
|
+
const id = doc._id;
|
|
800
|
+
return Buffer.from(JSON.stringify({ v, t, id: String(id) })).toString('base64url');
|
|
801
|
+
}
|
|
802
|
+
/** Decodes a cursor produced by encodeCursor(), restoring Date/ObjectId typing so comparisons stay type-correct. */
|
|
803
|
+
decodeCursor(cursor) {
|
|
804
|
+
let parsed;
|
|
805
|
+
try {
|
|
806
|
+
parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
|
|
807
|
+
}
|
|
808
|
+
catch {
|
|
809
|
+
throw new QueryAggregateValidationError('paginateCursor: invalid cursor');
|
|
810
|
+
}
|
|
811
|
+
let v = parsed.v;
|
|
812
|
+
if (parsed.t === 'date' && typeof v === 'string')
|
|
813
|
+
v = new Date(v);
|
|
814
|
+
if (parsed.t === 'objectid' &&
|
|
815
|
+
typeof v === 'string' &&
|
|
816
|
+
(0, mongoose_1.isValidObjectId)(v)) {
|
|
817
|
+
v = new mongoose_1.Types.ObjectId(v);
|
|
818
|
+
}
|
|
819
|
+
return { v, id: parsed.id };
|
|
820
|
+
}
|
|
633
821
|
/** Base pipeline shared by every execution path: match -> lookups/custom stages -> project -> sort. */
|
|
634
822
|
buildBasePipeline() {
|
|
635
823
|
const pipeline = [];
|
|
@@ -736,6 +924,164 @@ class QueryAggregate {
|
|
|
736
924
|
hasPrevPage: page > 1,
|
|
737
925
|
};
|
|
738
926
|
}
|
|
927
|
+
// ── Advanced terminal & utility methods (additive — paginate() above is
|
|
928
|
+
// untouched) ─────────────────────────────────────────────────────────────
|
|
929
|
+
/** Returns just the matching document count — cheaper than paginate() when you don't need the data page. Ignores $project/$sort. */
|
|
930
|
+
async count() {
|
|
931
|
+
const pipeline = [
|
|
932
|
+
...this.buildMatchAndStagesPipeline(),
|
|
933
|
+
{ $count: 'count' },
|
|
934
|
+
];
|
|
935
|
+
const [row] = await this.execAggregate(pipeline);
|
|
936
|
+
return row?.count ?? 0;
|
|
937
|
+
}
|
|
938
|
+
/** Returns the distinct values of `field` for the current filter/where/range conditions. */
|
|
939
|
+
async distinct(field) {
|
|
940
|
+
const pipeline = [
|
|
941
|
+
...this.buildMatchAndStagesPipeline(),
|
|
942
|
+
{ $group: { _id: `$${field}` } },
|
|
943
|
+
];
|
|
944
|
+
const rows = await this.execAggregate(pipeline);
|
|
945
|
+
return rows.map((r) => r._id);
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* Computes one or more aggregate metrics (sum/avg/min/max/count) over the
|
|
949
|
+
* current filter/where/range conditions in a single round trip — handy for
|
|
950
|
+
* dashboard totals ("revenue", "avgOrderValue", "orderCount", ...).
|
|
951
|
+
* Ignores $project/$sort/pagination.
|
|
952
|
+
*/
|
|
953
|
+
async stats(specs) {
|
|
954
|
+
const group = { _id: null };
|
|
955
|
+
for (const spec of specs) {
|
|
956
|
+
if (spec.op === 'count') {
|
|
957
|
+
group[spec.name] = { $sum: 1 };
|
|
958
|
+
}
|
|
959
|
+
else {
|
|
960
|
+
if (!spec.field) {
|
|
961
|
+
throw new QueryAggregateValidationError(`stats: metric "${spec.name}" needs a "field" for op "${spec.op}"`);
|
|
962
|
+
}
|
|
963
|
+
group[spec.name] = { [`$${spec.op}`]: `$${spec.field}` };
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
const pipeline = [
|
|
967
|
+
...this.buildMatchAndStagesPipeline(),
|
|
968
|
+
{ $group: group },
|
|
969
|
+
];
|
|
970
|
+
const [row] = await this.execAggregate(pipeline);
|
|
971
|
+
const out = {};
|
|
972
|
+
for (const spec of specs)
|
|
973
|
+
out[spec.name] = row?.[spec.name] ?? 0;
|
|
974
|
+
return out;
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* Streams results as an async-iterable cursor instead of buffering the
|
|
978
|
+
* whole page in memory — use for large exports (CSV generation, bulk
|
|
979
|
+
* processing) with `for await (const doc of qa.stream())`. Ignores
|
|
980
|
+
* page/limit; add your own $limit via .addStage() if you want a cap.
|
|
981
|
+
*/
|
|
982
|
+
stream() {
|
|
983
|
+
const pipeline = this.buildBasePipeline();
|
|
984
|
+
const agg = this.model.aggregate(pipeline);
|
|
985
|
+
if (this.options.maxTimeMS > 0)
|
|
986
|
+
agg.option({ maxTimeMS: this.options.maxTimeMS });
|
|
987
|
+
if (this.options.allowDiskUse)
|
|
988
|
+
agg.allowDiskUse(true);
|
|
989
|
+
return agg.cursor();
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Keyset ("seek") pagination — scales far better than .paginate()'s
|
|
993
|
+
* $skip on deep pages of large collections, at the cost of not supporting
|
|
994
|
+
* "jump to page N". Requires .sort() to have been called with exactly the
|
|
995
|
+
* field you want to seek on (falls back to DEFAULT_SORT's `createdAt`
|
|
996
|
+
* otherwise). Pass the previous page's `nextCursor` back in as `cursor`
|
|
997
|
+
* to continue; a `hasNextPage: false` / `nextCursor: null` page is the end.
|
|
998
|
+
*/
|
|
999
|
+
async paginateCursor(opts = {}) {
|
|
1000
|
+
const limit = opts.limit && opts.limit > 0
|
|
1001
|
+
? Math.min(opts.limit, this.options.maxLimit)
|
|
1002
|
+
: this._limit;
|
|
1003
|
+
const [sortField, sortDir] = Object.entries(this._sort)[0] ?? [
|
|
1004
|
+
'createdAt',
|
|
1005
|
+
-1,
|
|
1006
|
+
];
|
|
1007
|
+
const pipeline = this.buildMatchAndStagesPipeline();
|
|
1008
|
+
if (opts.cursor) {
|
|
1009
|
+
const { v, id } = this.decodeCursor(opts.cursor);
|
|
1010
|
+
const cmp = sortDir === -1 ? '$lt' : '$gt';
|
|
1011
|
+
const idValue = (0, mongoose_1.isValidObjectId)(id) ? new mongoose_1.Types.ObjectId(id) : id;
|
|
1012
|
+
pipeline.push({
|
|
1013
|
+
$match: {
|
|
1014
|
+
$or: [
|
|
1015
|
+
{ [sortField]: { [cmp]: v } },
|
|
1016
|
+
{ [sortField]: v, _id: { [cmp]: idValue } },
|
|
1017
|
+
],
|
|
1018
|
+
},
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
if (this._projection)
|
|
1022
|
+
pipeline.push({ $project: this._projection });
|
|
1023
|
+
pipeline.push({ $sort: { [sortField]: sortDir, _id: sortDir } });
|
|
1024
|
+
pipeline.push({ $limit: limit + 1 });
|
|
1025
|
+
const rows = await this.execAggregate(pipeline);
|
|
1026
|
+
const hasNextPage = rows.length > limit;
|
|
1027
|
+
const data = (hasNextPage ? rows.slice(0, limit) : rows);
|
|
1028
|
+
const nextCursor = hasNextPage
|
|
1029
|
+
? this.encodeCursor(data[data.length - 1], sortField)
|
|
1030
|
+
: null;
|
|
1031
|
+
return { data, limit, nextCursor, hasNextPage };
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Runs the built pipeline through Mongoose's .explain() for debugging
|
|
1035
|
+
* slow queries / verifying index usage. Never use in a hot request path —
|
|
1036
|
+
* this is a development/ops tool.
|
|
1037
|
+
*/
|
|
1038
|
+
async explain(verbosity = 'queryPlanner') {
|
|
1039
|
+
const pipeline = this.buildBasePipeline();
|
|
1040
|
+
return this.model.aggregate(pipeline).explain(verbosity);
|
|
1041
|
+
}
|
|
1042
|
+
/** Convenience wrapper over addStage() for a computed $addFields entry, e.g. .computeField('margin', { $subtract: ['$price', '$cost'] }). */
|
|
1043
|
+
computeField(name, expression) {
|
|
1044
|
+
return this.addStage({
|
|
1045
|
+
$addFields: { [name]: expression },
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
/** Convenience server-side condition excluding soft-deleted docs (matches both `null` and a missing field, per MongoDB equality semantics). Not client-overridable. */
|
|
1049
|
+
excludeSoftDeleted(field = 'deletedAt') {
|
|
1050
|
+
this._serverConditions[field] = null;
|
|
1051
|
+
return this;
|
|
1052
|
+
}
|
|
1053
|
+
/** Applies .where(conditions) only when `condition` is truthy — avoids scattering if-statements around chained builder calls. */
|
|
1054
|
+
whereIf(condition, conditions) {
|
|
1055
|
+
if (condition)
|
|
1056
|
+
this.where(conditions);
|
|
1057
|
+
return this;
|
|
1058
|
+
}
|
|
1059
|
+
/** Deep-copies the current builder state (filters, sort, projection, stages) into a new independent instance — handy for branching one shared base query into e.g. both .paginate() and .stats() without rebuilding it twice. */
|
|
1060
|
+
clone() {
|
|
1061
|
+
const copy = new QueryAggregate(this.model, this.qs, this.options);
|
|
1062
|
+
copy._allowedLookup = new Set(this._allowedLookup);
|
|
1063
|
+
copy._canonicalMap = new Map(this._canonicalMap);
|
|
1064
|
+
copy._dateFieldsLookup = this._dateFieldsLookup
|
|
1065
|
+
? new Set(this._dateFieldsLookup)
|
|
1066
|
+
: null;
|
|
1067
|
+
copy._objectIdFieldsLookup = this._objectIdFieldsLookup
|
|
1068
|
+
? new Set(this._objectIdFieldsLookup)
|
|
1069
|
+
: null;
|
|
1070
|
+
copy._urlFilter = { ...this._urlFilter };
|
|
1071
|
+
copy._serverConditions = { ...this._serverConditions };
|
|
1072
|
+
copy._searchOr = [...this._searchOr];
|
|
1073
|
+
copy._sort = { ...this._sort };
|
|
1074
|
+
copy._projection = this._projection ? { ...this._projection } : null;
|
|
1075
|
+
copy._defaultProjection = this._defaultProjection
|
|
1076
|
+
? { ...this._defaultProjection }
|
|
1077
|
+
: null;
|
|
1078
|
+
copy._stages = [...this._stages];
|
|
1079
|
+
return copy;
|
|
1080
|
+
}
|
|
1081
|
+
/** Returns the fully-built pipeline without executing it — for logging, snapshot tests, or sanity-checking what will actually run. */
|
|
1082
|
+
debugPipeline() {
|
|
1083
|
+
return this.buildBasePipeline();
|
|
1084
|
+
}
|
|
739
1085
|
}
|
|
740
1086
|
exports.QueryAggregate = QueryAggregate;
|
|
741
1087
|
exports.default = QueryAggregate;
|