mongoose-query-find 2.1.1 → 3.0.1
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 +136 -50
- package/dist/index.d.ts +116 -61
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +460 -173
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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
|
-
- [.
|
|
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
|
|
56
|
+
import { queryFind } from 'mongoose-query-find';
|
|
54
57
|
import UserModel from './models/user';
|
|
55
58
|
|
|
56
|
-
const result = await
|
|
59
|
+
const result = await queryFind(UserModel.find(), req.query)
|
|
60
|
+
.allowFields(['name', 'email', 'role', 'createdAt'])
|
|
61
|
+
.where({ deletedAt: null })
|
|
57
62
|
.filter()
|
|
58
|
-
.
|
|
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
|
|
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
|
-
-
|
|
102
|
-
- Coerces date-like
|
|
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
|
-
### `.
|
|
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
|
-
|
|
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
|
-
.
|
|
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
|
|
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
|
|
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
|
|
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.
|
|
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 —
|
|
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>>`.
|
|
251
|
+
Executes the query and returns a `Promise<PaginatedResult<T>>`.
|
|
199
252
|
|
|
200
|
-
|
|
201
|
-
|
|
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[];
|
|
212
|
-
total: number;
|
|
213
|
-
page: number;
|
|
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
|
-
|
|
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`,
|
|
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 (
|
|
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
|
|
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
|
|
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
|
-
.
|
|
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[
|
|
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
|
-
|
|
342
|
+
All types are exported:
|
|
285
343
|
|
|
286
344
|
```ts
|
|
287
|
-
import
|
|
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,24 @@
|
|
|
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
|
+
* - Deep recursive operator-key coercion (eq/ne/gt/... → $eq/$ne/$gt/...), applied
|
|
16
|
+
* ONLY to object keys — never to string values (fixes JSON-string regex bug)
|
|
17
|
+
* - estimatedDocumentCount fast-path when no filter is applied
|
|
18
|
+
* - Query timeout via maxTimeMS (prevents runaway queries)
|
|
19
|
+
* - Structured error types for clean upstream handling
|
|
20
|
+
* - Zero external runtime dependencies beyond mongoose
|
|
21
|
+
*/
|
|
1
22
|
import { Model, PopulateOptions, Query } from 'mongoose';
|
|
2
23
|
export interface QueryParams {
|
|
3
24
|
page?: string;
|
|
@@ -13,99 +34,133 @@ export interface PaginatedResult<T> {
|
|
|
13
34
|
page: number;
|
|
14
35
|
totalPages: number;
|
|
15
36
|
limit: number;
|
|
37
|
+
hasNextPage: boolean;
|
|
38
|
+
hasPrevPage: boolean;
|
|
39
|
+
}
|
|
40
|
+
export interface QueryFindOptions {
|
|
41
|
+
/**
|
|
42
|
+
* Maximum time in milliseconds MongoDB is allowed to spend on the query.
|
|
43
|
+
* Defaults to 5000ms. Pass 0 to disable.
|
|
44
|
+
*/
|
|
45
|
+
maxTimeMS?: number;
|
|
46
|
+
}
|
|
47
|
+
export declare class QueryFindError extends Error {
|
|
48
|
+
constructor(message: string);
|
|
49
|
+
}
|
|
50
|
+
export declare class QueryFindValidationError extends QueryFindError {
|
|
51
|
+
constructor(message: string);
|
|
16
52
|
}
|
|
17
53
|
/**
|
|
18
|
-
*
|
|
19
|
-
* then paginates the result using two native `countDocuments` + `find` calls
|
|
20
|
-
* (no aggregation pipeline required).
|
|
21
|
-
*
|
|
22
|
-
* Base query conditions passed to the constructor (e.g. `Model.find({ role: 'admin' })`)
|
|
23
|
-
* are automatically preserved and merged with any additional filters applied
|
|
24
|
-
* via `.filter()` or `.globalFilter()`.
|
|
54
|
+
* Production-grade fluent query builder / paginator for Mongoose 8/9.
|
|
25
55
|
*
|
|
26
56
|
* @example
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* )
|
|
57
|
+
* ```ts
|
|
58
|
+
* const result = await queryFind(User.find(), req.query)
|
|
59
|
+
* .allowFields(['name', 'email', 'role', 'createdAt'])
|
|
60
|
+
* .where({ orgId: req.user.orgId, deletedAt: null })
|
|
31
61
|
* .filter()
|
|
32
|
-
* .
|
|
62
|
+
* .globalSearch(['name', 'email'])
|
|
33
63
|
* .sort()
|
|
34
|
-
* .limitFields('-__v')
|
|
35
|
-
* .populate('
|
|
36
|
-
* .populate({ path: 'comments', select: 'text createdAt' })
|
|
64
|
+
* .limitFields('-password -__v')
|
|
65
|
+
* .populate('department', 'name')
|
|
37
66
|
* .paginate();
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* Security notes:
|
|
70
|
+
* - `.allowFields()` before `.filter()` restricts which URL params reach Mongo.
|
|
71
|
+
* - `.where()` conditions are hard — URL cannot override them.
|
|
72
|
+
* - Unknown/banned $ operators throw QueryFindValidationError (checked recursively).
|
|
73
|
+
* - Nesting depth capped at 5; page size capped at 100; sort fields capped at 5.
|
|
74
|
+
* - Search terms are regex-escaped (ReDoS prevention) and length-capped at 200 chars.
|
|
75
|
+
* - ?fields= projection is allowlist-filtered to prevent sensitive field leakage.
|
|
76
|
+
* - Operator-key coercion (eq/gte/in/...) only touches object KEYS, never string
|
|
77
|
+
* VALUES — a search like ?name=eq or ?status=in cannot be corrupted into a
|
|
78
|
+
* Mongo operator.
|
|
79
|
+
* - All queries run with maxTimeMS to prevent runaway collection scans.
|
|
38
80
|
*/
|
|
39
|
-
declare class QueryFind<TRawDocType, TModelType extends Model<TRawDocType> = Model<TRawDocType>> {
|
|
81
|
+
export declare class QueryFind<TRawDocType, TModelType extends Model<TRawDocType> = Model<TRawDocType>> {
|
|
40
82
|
private readonly model;
|
|
41
|
-
private readonly
|
|
42
|
-
|
|
43
|
-
private
|
|
44
|
-
|
|
45
|
-
private
|
|
46
|
-
|
|
47
|
-
private
|
|
48
|
-
|
|
49
|
-
private populateOptions;
|
|
50
|
-
constructor(query: Query<TRawDocType[], TRawDocType>, queryString: QueryParams);
|
|
83
|
+
private readonly qs;
|
|
84
|
+
private readonly options;
|
|
85
|
+
private _allowedFields;
|
|
86
|
+
private _filter;
|
|
87
|
+
private _sort;
|
|
88
|
+
private _select;
|
|
89
|
+
private _populates;
|
|
90
|
+
constructor(query: Query<TRawDocType[], TRawDocType>, queryString: QueryParams, options?: QueryFindOptions);
|
|
51
91
|
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
92
|
+
* Declare which fields may appear in URL filters, sort, and projection.
|
|
93
|
+
* Call before `.filter()`, `.sort()`, and `.limitFields()`.
|
|
54
94
|
*/
|
|
95
|
+
allowFields(fields: string[]): this;
|
|
96
|
+
/** Parse URL query params into a Mongoose filter (respects allowlist). */
|
|
55
97
|
filter(): this;
|
|
56
98
|
/**
|
|
57
|
-
*
|
|
58
|
-
*
|
|
99
|
+
* Apply mandatory server-side conditions the URL cannot override.
|
|
100
|
+
* Use for multi-tenancy, soft-delete exclusion, etc.
|
|
101
|
+
*
|
|
102
|
+
* @example .where({ orgId: req.user.orgId, deletedAt: null })
|
|
103
|
+
*/
|
|
104
|
+
where(conditions: Partial<Record<keyof TRawDocType, unknown>>): this;
|
|
105
|
+
/**
|
|
106
|
+
* Case-insensitive full-text search across `fields` when `?q=` is present.
|
|
107
|
+
* Search term is regex-escaped (ReDoS prevention) and capped at 200 chars.
|
|
108
|
+
* Preserves any existing `$or` by lifting both into `$and`.
|
|
59
109
|
*/
|
|
60
|
-
|
|
110
|
+
globalSearch(fields: string[]): this;
|
|
61
111
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
112
|
+
* Apply sort from `?sort=`. Falls back to `{ createdAt: -1 }`.
|
|
113
|
+
* Fields not in the allowlist are silently skipped.
|
|
114
|
+
* Capped at MAX_SORT_FIELDS (5) fields.
|
|
64
115
|
*/
|
|
65
116
|
sort(): this;
|
|
66
117
|
/**
|
|
67
118
|
* Configure field projection.
|
|
119
|
+
* Priority: `?fields=` query param > `defaultFields` argument > no projection.
|
|
68
120
|
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* 3. No projection at all when both are absent (all fields returned).
|
|
121
|
+
* When `allowFields()` has been called, any field in `?fields=` that is not
|
|
122
|
+
* in the allowlist is stripped — preventing clients from projecting sensitive
|
|
123
|
+
* fields like `password` or `resetToken`.
|
|
73
124
|
*
|
|
74
|
-
* @param defaultFields -
|
|
75
|
-
*
|
|
76
|
-
* `?fields=` query param.
|
|
125
|
+
* @param defaultFields e.g. `'-password -__v'` — always excluded when the
|
|
126
|
+
* client does not supply `?fields=`.
|
|
77
127
|
*/
|
|
78
128
|
limitFields(defaultFields?: string): this;
|
|
79
129
|
/**
|
|
80
|
-
* Register a populate
|
|
81
|
-
* multiple paths — each call appends to the internal list.
|
|
82
|
-
*
|
|
83
|
-
* Accepts the same arguments as Mongoose's own `.populate()`:
|
|
84
|
-
* - A plain path string: `.populate('author')`
|
|
85
|
-
* - A path + select string: `.populate('author', 'name email')`
|
|
86
|
-
* - A full `PopulateOptions` object: `.populate({ path: 'comments', select: 'text', match: { visible: true } })`
|
|
130
|
+
* Register a populate path. Chainable; all entries applied in `paginate()`.
|
|
87
131
|
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
* @param path - Field path to populate, or a full `PopulateOptions` object.
|
|
93
|
-
* @param select - Optional field projection for the populated documents
|
|
94
|
-
* (only used when `path` is a plain string).
|
|
132
|
+
* @example
|
|
133
|
+
* .populate('author')
|
|
134
|
+
* .populate('author', 'name avatar')
|
|
135
|
+
* .populate({ path: 'comments', select: 'text', match: { visible: true } })
|
|
95
136
|
*/
|
|
96
137
|
populate(path: string | PopulateOptions, select?: string): this;
|
|
97
138
|
/**
|
|
98
|
-
* Execute
|
|
139
|
+
* Execute and return a paginated result.
|
|
99
140
|
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
141
|
+
* - count + find run fully in parallel via Promise.all (saves one round-trip).
|
|
142
|
+
* - Uses estimatedDocumentCount fast-path when no filter is applied (O(1)).
|
|
143
|
+
* - .lean() returns plain objects (~3-5× faster for read-only responses).
|
|
144
|
+
* - maxTimeMS applied to both count and find (prevents runaway scans).
|
|
145
|
+
* - page is clamped to 1 if it exceeds totalPages (safe mid-delete behavior).
|
|
104
146
|
*
|
|
105
|
-
*
|
|
106
|
-
* page 1 is returned instead so the caller always receives valid data.
|
|
147
|
+
* @throws {QueryFindValidationError} on disallowed $ operators in the URL.
|
|
107
148
|
*/
|
|
108
149
|
paginate(): Promise<PaginatedResult<TRawDocType>>;
|
|
109
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Convenience factory — avoids `new` at the call site.
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* const result = await queryFind(User.find(), req.query, { maxTimeMS: 3000 })
|
|
156
|
+
* .allowFields(['name', 'email', 'createdAt'])
|
|
157
|
+
* .where({ deletedAt: null })
|
|
158
|
+
* .filter()
|
|
159
|
+
* .globalSearch(['name', 'email'])
|
|
160
|
+
* .sort()
|
|
161
|
+
* .limitFields('-password -__v')
|
|
162
|
+
* .paginate();
|
|
163
|
+
*/
|
|
164
|
+
export declare function queryFind<T>(query: Query<T[], T>, queryString: QueryParams, options?: QueryFindOptions): QueryFind<T>;
|
|
110
165
|
export default QueryFind;
|
|
111
166
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAiB,EAAE,KAAK,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAuEnE,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,CAA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