mongoose-query-find 2.1.0 → 3.0.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 CHANGED
@@ -14,8 +14,10 @@ A fluent, chainable query builder for Mongoose that handles filtering, global se
14
14
  - [Quick Start](#quick-start)
15
15
  - [Constructor](#constructor)
16
16
  - [Builder Methods](#builder-methods)
17
+ - [.allowFields()](#allowfieldsfields-string)
17
18
  - [.filter()](#filter)
18
- - [.globalFilter()](#globalfilterfields-string)
19
+ - [.where()](#whereconditions)
20
+ - [.globalSearch()](#globalsearchfields-string)
19
21
  - [.sort()](#sort)
20
22
  - [.limitFields()](#limitfieldsdefaultfields-string)
21
23
  - [.populate()](#populatepath-string--populateoptions-select-string)
@@ -24,6 +26,7 @@ A fluent, chainable query builder for Mongoose that handles filtering, global se
24
26
  - [Query Parameter Reference](#query-parameter-reference)
25
27
  - [Full Example (Express)](#full-example-express)
26
28
  - [TypeScript Types](#typescript-types)
29
+ - [Security](#security)
27
30
  - [Links](#links)
28
31
  - [License](#license)
29
32
 
@@ -50,12 +53,14 @@ pnpm add mongoose-query-find
50
53
  ## Quick Start
51
54
 
52
55
  ```ts
53
- import QueryFind from 'mongoose-query-find';
56
+ import { queryFind } from 'mongoose-query-find';
54
57
  import UserModel from './models/user';
55
58
 
56
- const result = await new QueryFind(UserModel.find(), req.query)
59
+ const result = await queryFind(UserModel.find(), req.query)
60
+ .allowFields(['name', 'email', 'role', 'createdAt'])
61
+ .where({ deletedAt: null })
57
62
  .filter()
58
- .globalFilter(['name', 'email'])
63
+ .globalSearch(['name', 'email'])
59
64
  .sort()
60
65
  .limitFields('-password -__v')
61
66
  .paginate();
@@ -69,7 +74,9 @@ const result = await new QueryFind(UserModel.find(), req.query)
69
74
  "total": 84,
70
75
  "page": 2,
71
76
  "totalPages": 9,
72
- "limit": 10
77
+ "limit": 10,
78
+ "hasNextPage": true,
79
+ "hasPrevPage": true
73
80
  }
74
81
  ```
75
82
 
@@ -78,19 +85,46 @@ const result = await new QueryFind(UserModel.find(), req.query)
78
85
  ## Constructor
79
86
 
80
87
  ```ts
81
- new QueryFind(query, queryString);
88
+ new QueryFind(query, queryString, options?);
89
+ // or use the factory function (recommended):
90
+ queryFind(query, queryString, options?);
82
91
  ```
83
92
 
84
- | Parameter | Type | Description |
85
- | ------------- | ----------------------------------- | --------------------------------------------- |
86
- | `query` | `Query<TRawDocType[], TRawDocType>` | A Mongoose query, e.g. `Model.find()` |
87
- | `queryString` | `QueryParams` | The parsed URL query object, e.g. `req.query` |
93
+ | Parameter | Type | Description |
94
+ | ------------- | ----------------------------------- | ----------------------------------------------------- |
95
+ | `query` | `Query<TRawDocType[], TRawDocType>` | A Mongoose query, e.g. `Model.find()` |
96
+ | `queryString` | `QueryParams` | The parsed URL query object, e.g. `req.query` |
97
+ | `options` | `QueryFindOptions` _(optional)_ | Configuration options (see [Options](#options) below) |
98
+
99
+ ### Options
100
+
101
+ | Option | Type | Default | Description |
102
+ | ----------- | -------- | ------- | ---------------------------------------------------------------------- |
103
+ | `maxTimeMS` | `number` | `5000` | Max milliseconds MongoDB may spend on each query. Pass `0` to disable. |
88
104
 
89
105
  ---
90
106
 
91
107
  ## Builder Methods
92
108
 
93
- All builder methods return `this`, so they are fully chainable in any order.
109
+ All builder methods return `this` and are fully chainable. The recommended call order is:
110
+
111
+ ```
112
+ allowFields → where → filter → globalSearch → sort → limitFields → populate → paginate
113
+ ```
114
+
115
+ ---
116
+
117
+ ### `.allowFields(fields: string[])`
118
+
119
+ Declares which fields may appear in URL filters, sort parameters, and field projections. Acts as an allowlist — any field not listed is silently stripped from client input before it reaches MongoDB.
120
+
121
+ **Call this before `.filter()`, `.sort()`, and `.limitFields()`.**
122
+
123
+ ```ts
124
+ .allowFields(['name', 'email', 'role', 'createdAt'])
125
+ ```
126
+
127
+ ---
94
128
 
95
129
  ### `.filter()`
96
130
 
@@ -98,8 +132,9 @@ Parses the URL query string into a Mongoose filter. Automatically:
98
132
 
99
133
  - Strips reserved keys (`page`, `limit`, `sort`, `fields`, `q`)
100
134
  - Converts comparison operator names to MongoDB `$` syntax (`gt` → `$gt`, `lte` → `$lte`, etc.)
101
- - Coerces string booleans to real booleans (`"true"` → `true`, `"false"` → `false`)
102
- - Coerces date-like string values to `Date` instances for fields named `createdAt`, `updatedAt`, `deletedAt`, `date`, or `Date`
135
+ - Recursively coerces string booleans to real booleans (`"true"` → `true`, `"false"` → `false`)
136
+ - Coerces date-like strings to `Date` instances for fields named `createdAt`, `updatedAt`, `deletedAt`, `date`, `birthDate`, or `expiresAt`
137
+ - Recursively validates and rejects banned operators (`$where`, `$expr`, `$function`, etc.)
103
138
 
104
139
  **Supported operators:** `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`
105
140
 
@@ -114,24 +149,40 @@ GET /users?age[gte]=18&isActive=true&role=admin
114
149
 
115
150
  ---
116
151
 
117
- ### `.globalFilter(fields: string[])`
152
+ ### `.where(conditions)`
153
+
154
+ Applies mandatory server-side conditions that the URL **cannot override**. Use this for multi-tenancy, soft-delete exclusion, and any security-critical constraints.
155
+
156
+ ```ts
157
+ .where({ orgId: req.user.orgId, deletedAt: null })
158
+ ```
159
+
160
+ > `.where()` always wins — conditions are merged after `.filter()` and will overwrite any conflicting URL params.
161
+
162
+ ---
163
+
164
+ ### `.globalSearch(fields: string[])`
165
+
166
+ Adds a case-insensitive `$or` regex search across the specified fields when the `?q=` query parameter is present. If `q` is absent or exceeds 200 characters, this method is a no-op.
118
167
 
119
- Adds a case-insensitive `$or` regex search across the specified fields when the `q` query parameter is present. If `q` is absent, this method is a no-op.
168
+ Search terms are regex-escaped to prevent ReDoS attacks.
120
169
 
121
170
  ```
122
171
  GET /users?q=john
123
172
  ```
124
173
 
125
174
  ```ts
126
- .globalFilter(['name', 'email'])
175
+ .globalSearch(['name', 'email'])
127
176
  // → { $or: [{ name: /john/i }, { email: /john/i }] }
128
177
  ```
129
178
 
179
+ If a `$or` clause already exists in the filter (e.g. from `.filter()`), both are safely merged under `$and`.
180
+
130
181
  ---
131
182
 
132
183
  ### `.sort()`
133
184
 
134
- Applies sort order from the `sort` query parameter. Prefix a field with `-` for descending order. Multiple fields are comma-separated.
185
+ Applies sort order from the `?sort=` query parameter. Prefix a field with `-` for descending order. Multiple fields are comma-separated, capped at 5 fields.
135
186
 
136
187
  ```
137
188
  GET /users?sort=-createdAt,name
@@ -142,19 +193,21 @@ GET /users?sort=-createdAt,name
142
193
  // → sorts by createdAt DESC, then name ASC
143
194
  ```
144
195
 
145
- Defaults to `{ createdAt: -1 }` when the `sort` param is absent.
196
+ Defaults to `{ createdAt: -1 }` when the `sort` param is absent. Fields not in the allowlist are silently skipped.
146
197
 
147
198
  ---
148
199
 
149
200
  ### `.limitFields(defaultFields?: string)`
150
201
 
151
- Controls which fields are returned (projection). Uses the `fields` query param when present, otherwise falls back to `defaultFields`.
202
+ Controls which fields are returned (projection). Uses the `?fields=` query param when present, otherwise falls back to `defaultFields`.
203
+
204
+ Fields requested via `?fields=` are filtered against the allowlist — clients cannot project sensitive fields like `password` or `resetToken`.
152
205
 
153
206
  **Priority order:**
154
207
 
155
- 1. `?fields=` query param — always wins when present
208
+ 1. `?fields=` query param — always wins when present (allowlist-filtered)
156
209
  2. `defaultFields` argument — used as fallback when no query param
157
- 3. No projection at all when both are absent (all fields returned)
210
+ 3. No projection when both are absent (all fields returned)
158
211
 
159
212
  ```
160
213
  GET /users?fields=name,email,role
@@ -170,7 +223,7 @@ GET /users?fields=name,email,role
170
223
 
171
224
  ### `.populate(path: string | PopulateOptions, select?: string)`
172
225
 
173
- Registers a populate directive. Can be called multiple times to populate multiple paths — each call appends to the internal list. All registered populates are applied inside `paginate()` after the `find` query is built, so core filter / sort / pagination logic is completely untouched.
226
+ Registers a populate directive. Chainable — each call appends to the internal list. All registered populates are applied inside `paginate()`.
174
227
 
175
228
  Accepts the same arguments as Mongoose's own `.populate()`:
176
229
 
@@ -184,7 +237,7 @@ Accepts the same arguments as Mongoose's own `.populate()`:
184
237
  // Full PopulateOptions object
185
238
  .populate({ path: 'comments', select: 'text createdAt', match: { visible: true } })
186
239
 
187
- // Multiple calls — each appends to the list
240
+ // Multiple calls — fully chainable
188
241
  .populate('author')
189
242
  .populate({ path: 'comments', select: 'text createdAt' })
190
243
  ```
@@ -195,10 +248,13 @@ Accepts the same arguments as Mongoose's own `.populate()`:
195
248
 
196
249
  ### `.paginate()`
197
250
 
198
- Executes the query and returns a `Promise<PaginatedResult<T>>`. Makes exactly two database round-trips:
251
+ Executes the query and returns a `Promise<PaginatedResult<T>>`.
199
252
 
200
- 1. `countDocuments` — counts total matching documents (uses index scan)
201
- 2. `find` — fetches the requested page with sort, skip, limit, projection, and any registered populates applied
253
+ - `countDocuments` and `find` run **in parallel** via `Promise.all` (saves one network round-trip).
254
+ - Uses `estimatedDocumentCount` as a fast-path when no filter is applied (O(1) vs O(n)).
255
+ - `.lean()` is applied for ~3–5× faster reads on plain object responses.
256
+ - `maxTimeMS` is applied to both count and find to prevent runaway collection scans.
257
+ - If the requested `page` exceeds `totalPages` (e.g. after a deletion), page `1` is returned automatically.
202
258
 
203
259
  ```
204
260
  GET /users?page=2&limit=20
@@ -208,30 +264,30 @@ GET /users?page=2&limit=20
208
264
 
209
265
  ```ts
210
266
  {
211
- data: T[]; // Documents for the current page
212
- total: number; // Total matching documents across all pages
213
- page: number; // Current page (auto-corrects to 1 if out of range)
267
+ data: T[];
268
+ total: number; // Total matching documents across all pages
269
+ page: number; // Current page (auto-corrects to 1 if out of range)
214
270
  totalPages: number;
215
271
  limit: number;
272
+ hasNextPage: boolean;
273
+ hasPrevPage: boolean;
216
274
  }
217
275
  ```
218
276
 
219
- > If the requested `page` exceeds `totalPages` (e.g. after a deletion), page `1` is returned automatically so the caller always receives valid data.
220
-
221
- **Defaults:** `page=1`, `limit=10`
277
+ **Defaults:** `page=1`, `limit=10`, max `limit=100`.
222
278
 
223
279
  ---
224
280
 
225
281
  ## Query Parameter Reference
226
282
 
227
- | Parameter | Example | Description |
228
- | ----------- | ------------------------- | ------------------------------------------------- |
229
- | `page` | `?page=3` | Page number (default: `1`, min: `1`) |
230
- | `limit` | `?limit=25` | Documents per page (default: `10`, min: `1`) |
231
- | `sort` | `?sort=-createdAt,name` | Sort fields; prefix `-` for descending |
232
- | `fields` | `?fields=name,email` | Comma-separated fields to include in the response |
233
- | `q` | `?q=john` | Global search term (used by `.globalFilter()`) |
234
- | _(any key)_ | `?role=admin&age[gte]=18` | Field-level filters processed by `.filter()` |
283
+ | Parameter | Example | Description |
284
+ | ----------- | ------------------------- | ------------------------------------------------------ |
285
+ | `page` | `?page=3` | Page number (default: `1`, min: `1`) |
286
+ | `limit` | `?limit=25` | Documents per page (default: `10`, max: `100`) |
287
+ | `sort` | `?sort=-createdAt,name` | Sort fields; prefix `-` for descending (max: 5 fields) |
288
+ | `fields` | `?fields=name,email` | Comma-separated fields to include in the response |
289
+ | `q` | `?q=john` | Global search term (max: 200 chars) |
290
+ | _(any key)_ | `?role=admin&age[gte]=18` | Field-level filters processed by `.filter()` |
235
291
 
236
292
  ---
237
293
 
@@ -239,22 +295,21 @@ GET /users?page=2&limit=20
239
295
 
240
296
  ```ts
241
297
  import { Request, Response } from 'express';
242
- import QueryFind from 'mongoose-query-find';
298
+ import { queryFind } from 'mongoose-query-find';
243
299
  import UserModel from '../models/user';
244
300
 
245
301
  export const getUsers = async (req: Request, res: Response) => {
246
- const result = await new QueryFind(UserModel.find(), req.query)
302
+ const result = await queryFind(UserModel.find(), req.query)
303
+ .allowFields(['name', 'email', 'username', 'role', 'isActive', 'createdAt'])
304
+ .where({ orgId: req.user.orgId, deletedAt: null })
247
305
  .filter()
248
- .globalFilter(['name', 'email', 'username'])
306
+ .globalSearch(['name', 'email', 'username'])
249
307
  .sort()
250
308
  .limitFields('-password -__v')
251
309
  .populate('role', 'name permissions')
252
310
  .paginate();
253
311
 
254
- res.json({
255
- status: 'success',
256
- ...result,
257
- });
312
+ res.json({ status: 'success', ...result });
258
313
  };
259
314
  ```
260
315
 
@@ -270,8 +325,11 @@ GET /users?q=alice
270
325
  # Users older than 25, return only name and email
271
326
  GET /users?age[gt]=25&fields=name,email
272
327
 
328
+ # Filter by exact date
329
+ GET /users?createdAt=2024-06-01
330
+
273
331
  # Filter by date range
274
- GET /users?createdAt[$gte]=2024-01-01&createdAt[$lte]=2024-12-31
332
+ GET /users?createdAt[gte]=2024-01-01&createdAt[lte]=2024-12-31
275
333
 
276
334
  # Combined: search + filter + sort + pagination
277
335
  GET /users?q=john&role=editor&sort=-createdAt&page=1&limit=5
@@ -281,10 +339,16 @@ GET /users?q=john&role=editor&sort=-createdAt&page=1&limit=5
281
339
 
282
340
  ## TypeScript Types
283
341
 
284
- Both types are exported and available for use in your own code:
342
+ All types are exported:
285
343
 
286
344
  ```ts
287
- import QueryFind, { QueryParams, PaginatedResult } from 'mongoose-query-find';
345
+ import {
346
+ queryFind,
347
+ QueryFind,
348
+ QueryParams,
349
+ PaginatedResult,
350
+ QueryFindOptions,
351
+ } from 'mongoose-query-find';
288
352
  ```
289
353
 
290
354
  ```ts
@@ -303,11 +367,33 @@ interface PaginatedResult<T> {
303
367
  page: number;
304
368
  totalPages: number;
305
369
  limit: number;
370
+ hasNextPage: boolean;
371
+ hasPrevPage: boolean;
372
+ }
373
+
374
+ interface QueryFindOptions {
375
+ maxTimeMS?: number; // default: 5000
306
376
  }
307
377
  ```
308
378
 
309
379
  ---
310
380
 
381
+ ## Security
382
+
383
+ | Protection | Detail |
384
+ | --------------------------- | ---------------------------------------------------------------------------------------- |
385
+ | **NoSQL injection** | Allowlist enforced on filters, sort, and projection via `.allowFields()` |
386
+ | **Banned operators** | `$where`, `$expr`, `$function`, and others are rejected recursively at any nesting depth |
387
+ | **ReDoS** | Search terms are regex-escaped before compilation |
388
+ | **Oversized search** | `?q=` capped at 200 characters |
389
+ | **Deep nesting DoS** | Filter object nesting capped at depth 5 |
390
+ | **Page size DoS** | `limit` hard-capped at 100 |
391
+ | **Sort abuse** | Sort fields hard-capped at 5 |
392
+ | **Runaway queries** | `maxTimeMS` applied to both count and find (default: 5s) |
393
+ | **Sensitive field leakage** | `?fields=` projection stripped against allowlist |
394
+
395
+ ---
396
+
311
397
  ## Links
312
398
 
313
399
  - [npm](https://www.npmjs.com/package/mongoose-query-find)
package/dist/index.d.ts CHANGED
@@ -1,3 +1,22 @@
1
+ /**
2
+ * @file query-find.ts
3
+ * @description Production-grade fluent query builder for Mongoose 8.x / 9.x.
4
+ * @requires mongoose ^8.0.0 || ^9.0.0
5
+ *
6
+ * Features:
7
+ * - URL query string → Mongoose filter (sanitized, validated, coerced)
8
+ * - Global full-text search via $or regex
9
+ * - Flexible sort, field projection, and populate
10
+ * - count + find run fully in parallel (Promise.all)
11
+ * - Hard limits on page size, sort fields, search length, nesting depth (DoS protection)
12
+ * - Allowlist-based field filtering on filters, sort, AND projection (NoSQL injection prevention)
13
+ * - Deep recursive operator validation (catches nested $where, $expr, etc.)
14
+ * - Deep recursive boolean coercion (handles nested query objects)
15
+ * - estimatedDocumentCount fast-path when no filter is applied
16
+ * - Query timeout via maxTimeMS (prevents runaway queries)
17
+ * - Structured error types for clean upstream handling
18
+ * - Zero external runtime dependencies beyond mongoose
19
+ */
1
20
  import { Model, PopulateOptions, Query } from 'mongoose';
2
21
  export interface QueryParams {
3
22
  page?: string;
@@ -13,89 +32,130 @@ export interface PaginatedResult<T> {
13
32
  page: number;
14
33
  totalPages: number;
15
34
  limit: number;
35
+ hasNextPage: boolean;
36
+ hasPrevPage: boolean;
37
+ }
38
+ export interface QueryFindOptions {
39
+ /**
40
+ * Maximum time in milliseconds MongoDB is allowed to spend on the query.
41
+ * Defaults to 5000ms. Pass 0 to disable.
42
+ */
43
+ maxTimeMS?: number;
44
+ }
45
+ export declare class QueryFindError extends Error {
46
+ constructor(message: string);
47
+ }
48
+ export declare class QueryFindValidationError extends QueryFindError {
49
+ constructor(message: string);
16
50
  }
17
51
  /**
18
- * Fluent query builder that progressively refines a Mongoose query,
19
- * then paginates the result using two native `countDocuments` + `find` calls
20
- * (no aggregation pipeline required).
52
+ * Production-grade fluent query builder / paginator for Mongoose 8/9.
21
53
  *
22
54
  * @example
23
- * const result = await new QueryFind(Model.find(), req.query)
55
+ * ```ts
56
+ * const result = await queryFind(User.find(), req.query)
57
+ * .allowFields(['name', 'email', 'role', 'createdAt'])
58
+ * .where({ orgId: req.user.orgId, deletedAt: null })
24
59
  * .filter()
25
- * .globalFilter(['name', 'email'])
60
+ * .globalSearch(['name', 'email'])
26
61
  * .sort()
27
- * .limitFields('-__v')
28
- * .populate('author')
29
- * .populate({ path: 'comments', select: 'text createdAt' })
62
+ * .limitFields('-password -__v')
63
+ * .populate('department', 'name')
30
64
  * .paginate();
65
+ * ```
66
+ *
67
+ * Security notes:
68
+ * - `.allowFields()` before `.filter()` restricts which URL params reach Mongo.
69
+ * - `.where()` conditions are hard — URL cannot override them.
70
+ * - Unknown/banned $ operators throw QueryFindValidationError (checked recursively).
71
+ * - Nesting depth capped at 5; page size capped at 100; sort fields capped at 5.
72
+ * - Search terms are regex-escaped (ReDoS prevention) and length-capped at 200 chars.
73
+ * - ?fields= projection is allowlist-filtered to prevent sensitive field leakage.
74
+ * - All queries run with maxTimeMS to prevent runaway collection scans.
31
75
  */
32
- declare class QueryFind<TRawDocType, TModelType extends Model<TRawDocType> = Model<TRawDocType>> {
76
+ export declare class QueryFind<TRawDocType, TModelType extends Model<TRawDocType> = Model<TRawDocType>> {
33
77
  private readonly model;
34
- private readonly queryString;
35
- /** Accumulated Mongoose filter (populated by `filter()` and `globalFilter()`). */
36
- private filterQuery;
37
- /** Sort order applied in `paginate()`. */
38
- private sortQuery;
39
- /** Projection string applied in `paginate()`. */
40
- private selectQuery;
41
- /** Accumulated populate options — each call to `populate()` appends here. */
42
- private populateOptions;
43
- constructor(query: Query<TRawDocType[], TRawDocType>, queryString: QueryParams);
44
- /** Parse the URL query string into a Mongoose filter. */
78
+ private readonly qs;
79
+ private readonly options;
80
+ private _allowedFields;
81
+ private _filter;
82
+ private _sort;
83
+ private _select;
84
+ private _populates;
85
+ constructor(query: Query<TRawDocType[], TRawDocType>, queryString: QueryParams, options?: QueryFindOptions);
86
+ /**
87
+ * Declare which fields may appear in URL filters, sort, and projection.
88
+ * Call before `.filter()`, `.sort()`, and `.limitFields()`.
89
+ */
90
+ allowFields(fields: string[]): this;
91
+ /** Parse URL query params into a Mongoose filter (respects allowlist). */
45
92
  filter(): this;
46
93
  /**
47
- * Add a case-insensitive `$or` regex search across the supplied fields
48
- * when the query string contains a `q` parameter.
94
+ * Apply mandatory server-side conditions the URL cannot override.
95
+ * Use for multi-tenancy, soft-delete exclusion, etc.
96
+ *
97
+ * @example .where({ orgId: req.user.orgId, deletedAt: null })
49
98
  */
50
- globalFilter(fields: string[]): this;
99
+ where(conditions: Partial<Record<keyof TRawDocType, unknown>>): this;
51
100
  /**
52
- * Configure sort order from the `sort` query param.
53
- * Falls back to `{ createdAt: -1 }` when the param is absent.
101
+ * Case-insensitive full-text search across `fields` when `?q=` is present.
102
+ * Search term is regex-escaped (ReDoS prevention) and capped at 200 chars.
103
+ * Preserves any existing `$or` by lifting both into `$and`.
104
+ */
105
+ globalSearch(fields: string[]): this;
106
+ /**
107
+ * Apply sort from `?sort=`. Falls back to `{ createdAt: -1 }`.
108
+ * Fields not in the allowlist are silently skipped.
109
+ * Capped at MAX_SORT_FIELDS (5) fields.
54
110
  */
55
111
  sort(): this;
56
112
  /**
57
113
  * Configure field projection.
114
+ * Priority: `?fields=` query param > `defaultFields` argument > no projection.
58
115
  *
59
- * Priority order:
60
- * 1. `?fields=` query param (always wins when present).
61
- * 2. `defaultFields` argument (used as fallback when no query param).
62
- * 3. No projection at all when both are absent (all fields returned).
116
+ * When `allowFields()` has been called, any field in `?fields=` that is not
117
+ * in the allowlist is stripped — preventing clients from projecting sensitive
118
+ * fields like `password` or `resetToken`.
63
119
  *
64
- * @param defaultFields - Optional space- or comma-separated projection
65
- * string, e.g. `'-password -__v'`. Omit to rely solely on the
66
- * `?fields=` query param.
120
+ * @param defaultFields e.g. `'-password -__v'` — always excluded when the
121
+ * client does not supply `?fields=`.
67
122
  */
68
123
  limitFields(defaultFields?: string): this;
69
124
  /**
70
- * Register a populate directive. Can be called multiple times to populate
71
- * multiple paths — each call appends to the internal list.
72
- *
73
- * Accepts the same arguments as Mongoose's own `.populate()`:
74
- * - A plain path string: `.populate('author')`
75
- * - A path + select string: `.populate('author', 'name email')`
76
- * - A full `PopulateOptions` object: `.populate({ path: 'comments', select: 'text', match: { visible: true } })`
125
+ * Register a populate path. Chainable; all entries applied in `paginate()`.
77
126
  *
78
- * All registered populates are applied inside `paginate()` after the
79
- * `find` query is built — core filter / sort / pagination logic is
80
- * completely untouched.
81
- *
82
- * @param path - Field path to populate, or a full `PopulateOptions` object.
83
- * @param select - Optional field projection for the populated documents
84
- * (only used when `path` is a plain string).
127
+ * @example
128
+ * .populate('author')
129
+ * .populate('author', 'name avatar')
130
+ * .populate({ path: 'comments', select: 'text', match: { visible: true } })
85
131
  */
86
132
  populate(path: string | PopulateOptions, select?: string): this;
87
133
  /**
88
- * Execute the query and return a paginated result.
134
+ * Execute and return a paginated result.
89
135
  *
90
- * Two database round-trips are made:
91
- * 1. `countDocuments` with the current filter — O(index scan).
92
- * 2. `find` with filter, sort, skip, limit, projection, and any
93
- * registered populates.
136
+ * - count + find run fully in parallel via Promise.all (saves one round-trip).
137
+ * - Uses estimatedDocumentCount fast-path when no filter is applied (O(1)).
138
+ * - .lean() returns plain objects (~3-5× faster for read-only responses).
139
+ * - maxTimeMS applied to both count and find (prevents runaway scans).
140
+ * - page is clamped to 1 if it exceeds totalPages (safe mid-delete behavior).
94
141
  *
95
- * If the requested page exceeds `totalPages` (e.g. after a deletion),
96
- * page 1 is returned instead so the caller always receives valid data.
142
+ * @throws {QueryFindValidationError} on disallowed $ operators in the URL.
97
143
  */
98
144
  paginate(): Promise<PaginatedResult<TRawDocType>>;
99
145
  }
146
+ /**
147
+ * Convenience factory — avoids `new` at the call site.
148
+ *
149
+ * @example
150
+ * const result = await queryFind(User.find(), req.query, { maxTimeMS: 3000 })
151
+ * .allowFields(['name', 'email', 'createdAt'])
152
+ * .where({ deletedAt: null })
153
+ * .filter()
154
+ * .globalSearch(['name', 'email'])
155
+ * .sort()
156
+ * .limitFields('-password -__v')
157
+ * .paginate();
158
+ */
159
+ export declare function queryFind<T>(query: Query<T[], T>, queryString: QueryParams, options?: QueryFindOptions): QueryFind<T>;
100
160
  export default QueryFind;
101
161
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,KAAK,EAAe,MAAM,UAAU,CAAC;AAItE,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;CACf;AAwJD;;;;;;;;;;;;;;GAcG;AACH,cAAM,SAAS,CACb,WAAW,EACX,UAAU,SAAS,KAAK,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC,WAAW,CAAC;IAE1D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAa;IACnC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAc;IAE1C,kFAAkF;IAClF,OAAO,CAAC,WAAW,CAA+B;IAElD,0CAA0C;IAC1C,OAAO,CAAC,S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