mongoose-query-find 1.4.0 → 1.6.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 +170 -135
- package/dist/index.d.ts +63 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +156 -51
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,41 +1,10 @@
|
|
|
1
1
|
# mongoose-query-find
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/mongoose-query-find)
|
|
4
|
+
[](https://github.com/jsdev-robin/mongoose-query-find/blob/main/LICENSE)
|
|
5
|
+
[](https://mongoosejs.com)
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
[](https://opensource.org/licenses/ISC)
|
|
7
|
-
[](https://www.typescriptlang.org/)
|
|
8
|
-
[](https://mongoosejs.com/)
|
|
9
|
-
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
## Table of Contents
|
|
13
|
-
|
|
14
|
-
- [Features](#features)
|
|
15
|
-
- [Installation](#installation)
|
|
16
|
-
- [Quick Start](#quick-start)
|
|
17
|
-
- [API Reference](#api-reference)
|
|
18
|
-
- [filter()](#filter)
|
|
19
|
-
- [globalFilter(fields)](#globalfilterfields)
|
|
20
|
-
- [sort()](#sort)
|
|
21
|
-
- [limitFields()](#limitfields)
|
|
22
|
-
- [paginate()](#paginate)
|
|
23
|
-
- [exec()](#exec)
|
|
24
|
-
- [Query String Parameters](#query-string-parameters)
|
|
25
|
-
- [Examples](#examples)
|
|
26
|
-
- [License](#license)
|
|
27
|
-
|
|
28
|
-
---
|
|
29
|
-
|
|
30
|
-
## Features
|
|
31
|
-
|
|
32
|
-
- **Advanced Filtering** — Supports all MongoDB comparison, logical, and element operators via query string
|
|
33
|
-
- **Global Search** — Search across multiple fields simultaneously using `$or` with regex
|
|
34
|
-
- **Sorting** — Sort by one or multiple fields, ascending or descending
|
|
35
|
-
- **Field Limiting** — Select or exclude specific fields from results
|
|
36
|
-
- **Pagination** — Built-in page/limit handling with sensible defaults
|
|
37
|
-
- **Chainable API** — Fluent builder pattern for clean, readable query construction
|
|
38
|
-
- **Fully Typed** — Written in TypeScript with generics for strong type safety
|
|
7
|
+
A fluent, chainable query builder for Mongoose that handles filtering, global search, sorting, field projection, and pagination — all driven directly from URL query parameters with zero boilerplate.
|
|
39
8
|
|
|
40
9
|
---
|
|
41
10
|
|
|
@@ -45,187 +14,253 @@
|
|
|
45
14
|
npm install mongoose-query-find
|
|
46
15
|
```
|
|
47
16
|
|
|
48
|
-
|
|
17
|
+
```bash
|
|
18
|
+
yarn add mongoose-query-find
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pnpm add mongoose-query-find
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
> **Peer dependency:** requires `mongoose ^8` or `mongoose ^9` installed in your project.
|
|
49
26
|
|
|
50
27
|
---
|
|
51
28
|
|
|
52
29
|
## Quick Start
|
|
53
30
|
|
|
54
|
-
```
|
|
31
|
+
```ts
|
|
55
32
|
import QueryFind from 'mongoose-query-find';
|
|
56
|
-
import
|
|
57
|
-
import Product from './models/Product';
|
|
33
|
+
import UserModel from './models/user';
|
|
58
34
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
35
|
+
const result = await new QueryFind(UserModel.find(), req.query)
|
|
36
|
+
.filter()
|
|
37
|
+
.globalFilter(['name', 'email'])
|
|
38
|
+
.sort()
|
|
39
|
+
.limitFields('-password -__v')
|
|
40
|
+
.paginate();
|
|
41
|
+
```
|
|
65
42
|
|
|
66
|
-
|
|
43
|
+
`result` will look like:
|
|
67
44
|
|
|
68
|
-
|
|
69
|
-
|
|
45
|
+
```json
|
|
46
|
+
{
|
|
47
|
+
"data": [...],
|
|
48
|
+
"total": 84,
|
|
49
|
+
"page": 2,
|
|
50
|
+
"totalPages": 9,
|
|
51
|
+
"limit": 10
|
|
52
|
+
}
|
|
70
53
|
```
|
|
71
54
|
|
|
72
55
|
---
|
|
73
56
|
|
|
74
|
-
##
|
|
57
|
+
## Constructor
|
|
75
58
|
|
|
76
|
-
|
|
59
|
+
```ts
|
|
60
|
+
new QueryFind(query, queryString);
|
|
61
|
+
```
|
|
77
62
|
|
|
78
|
-
| Parameter | Type
|
|
79
|
-
| ------------- |
|
|
80
|
-
| `query` | `Query<
|
|
81
|
-
| `queryString` | `QueryParams`
|
|
63
|
+
| Parameter | Type | Description |
|
|
64
|
+
| ------------- | ----------------------------------- | --------------------------------------------- |
|
|
65
|
+
| `query` | `Query<TRawDocType[], TRawDocType>` | A Mongoose query, e.g. `Model.find()` |
|
|
66
|
+
| `queryString` | `QueryParams` | The parsed URL query object, e.g. `req.query` |
|
|
82
67
|
|
|
83
68
|
---
|
|
84
69
|
|
|
85
|
-
|
|
70
|
+
## Builder Methods
|
|
71
|
+
|
|
72
|
+
All builder methods return `this`, so they are fully chainable in any order.
|
|
73
|
+
|
|
74
|
+
### `.filter()`
|
|
86
75
|
|
|
87
|
-
|
|
76
|
+
Parses the URL query string into a Mongoose filter. Automatically:
|
|
88
77
|
|
|
89
|
-
|
|
78
|
+
- Strips reserved keys (`page`, `limit`, `sort`, `fields`, `q`)
|
|
79
|
+
- Converts comparison operator names to MongoDB `$` syntax (`gt` → `$gt`, `lte` → `$lte`, etc.)
|
|
80
|
+
- Coerces string booleans to real booleans (`"true"` → `true`, `"false"` → `false`)
|
|
90
81
|
|
|
91
|
-
**
|
|
82
|
+
**Supported operators:** `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`
|
|
92
83
|
|
|
93
84
|
```
|
|
94
|
-
GET /
|
|
85
|
+
GET /users?age[gte]=18&isActive=true&role=admin
|
|
95
86
|
```
|
|
96
87
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
88
|
+
```ts
|
|
89
|
+
.filter()
|
|
90
|
+
// → { age: { $gte: 18 }, isActive: true, role: 'admin' }
|
|
91
|
+
```
|
|
100
92
|
|
|
101
|
-
|
|
93
|
+
---
|
|
102
94
|
|
|
103
|
-
|
|
104
|
-
| --------- | ---------- | ------------------------------------- |
|
|
105
|
-
| `fields` | `string[]` | Array of field names to search across |
|
|
95
|
+
### `.globalFilter(fields: string[])`
|
|
106
96
|
|
|
107
|
-
|
|
97
|
+
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.
|
|
108
98
|
|
|
109
|
-
```typescript
|
|
110
|
-
new QueryFind(Product.find(), req.query)
|
|
111
|
-
.globalFilter(['name', 'description', 'brand'])
|
|
112
|
-
.paginate();
|
|
113
99
|
```
|
|
114
|
-
|
|
115
|
-
**Example URL:**
|
|
116
|
-
|
|
100
|
+
GET /users?q=john
|
|
117
101
|
```
|
|
118
|
-
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
.globalFilter(['name', 'email'])
|
|
105
|
+
// → { $or: [{ name: /john/i }, { email: /john/i }] }
|
|
119
106
|
```
|
|
120
107
|
|
|
121
108
|
---
|
|
122
109
|
|
|
123
|
-
###
|
|
110
|
+
### `.sort()`
|
|
124
111
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
**Example URLs:**
|
|
112
|
+
Applies sort order from the `sort` query parameter. Prefix a field with `-` for descending order. Multiple fields are comma-separated.
|
|
128
113
|
|
|
129
114
|
```
|
|
130
|
-
GET /
|
|
131
|
-
GET /api/products?sort=-price # descending by price
|
|
132
|
-
GET /api/products?sort=category,-price # category asc, price desc
|
|
115
|
+
GET /users?sort=-createdAt,name
|
|
133
116
|
```
|
|
134
117
|
|
|
135
|
-
|
|
118
|
+
```ts
|
|
119
|
+
.sort()
|
|
120
|
+
// → sorts by createdAt DESC, then name ASC
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Defaults to `{ createdAt: -1 }` when the `sort` param is absent.
|
|
136
124
|
|
|
137
|
-
|
|
125
|
+
---
|
|
138
126
|
|
|
139
|
-
|
|
127
|
+
### `.limitFields(defaultFields: string)`
|
|
140
128
|
|
|
141
|
-
|
|
129
|
+
Controls which fields are returned (projection). Uses the `fields` query param when present, otherwise falls back to `defaultFields`.
|
|
142
130
|
|
|
143
131
|
```
|
|
144
|
-
GET /
|
|
145
|
-
|
|
132
|
+
GET /users?fields=name,email,role
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
.limitFields('-password -__v')
|
|
137
|
+
// With ?fields=name,email,role → selects only name, email, role
|
|
138
|
+
// Without ?fields → excludes password and __v
|
|
146
139
|
```
|
|
147
140
|
|
|
148
141
|
---
|
|
149
142
|
|
|
150
|
-
|
|
143
|
+
## Terminal Method
|
|
151
144
|
|
|
152
|
-
|
|
145
|
+
### `.paginate()`
|
|
153
146
|
|
|
154
|
-
|
|
155
|
-
| --------- | ------- | -------------------------- |
|
|
156
|
-
| `page` | `1` | Page number (1-indexed) |
|
|
157
|
-
| `limit` | `100` | Number of results per page |
|
|
147
|
+
Executes the query and returns a `Promise<PaginatedResult<T>>`. Makes exactly two database round-trips:
|
|
158
148
|
|
|
159
|
-
|
|
149
|
+
1. `countDocuments` — counts total matching documents (uses index scan)
|
|
150
|
+
2. `find` — fetches the requested page with sort, skip, limit, and projection applied
|
|
160
151
|
|
|
161
152
|
```
|
|
162
|
-
GET /
|
|
153
|
+
GET /users?page=2&limit=20
|
|
163
154
|
```
|
|
164
155
|
|
|
165
|
-
|
|
156
|
+
**Returns:**
|
|
166
157
|
|
|
167
|
-
|
|
158
|
+
```ts
|
|
159
|
+
{
|
|
160
|
+
data: T[]; // Documents for the current page
|
|
161
|
+
total: number; // Total matching documents across all pages
|
|
162
|
+
page: number; // Current page (auto-corrects to 1 if out of range)
|
|
163
|
+
totalPages: number;
|
|
164
|
+
limit: number;
|
|
165
|
+
}
|
|
166
|
+
```
|
|
168
167
|
|
|
169
|
-
|
|
168
|
+
> If the requested `page` exceeds `totalPages` (e.g. after a deletion), page `1` is returned automatically so the caller always receives valid data.
|
|
170
169
|
|
|
171
|
-
|
|
172
|
-
const results = await features.exec();
|
|
173
|
-
```
|
|
170
|
+
**Defaults:** `page=1`, `limit=10`
|
|
174
171
|
|
|
175
172
|
---
|
|
176
173
|
|
|
177
|
-
## Query
|
|
174
|
+
## Query Parameter Reference
|
|
178
175
|
|
|
179
|
-
| Parameter
|
|
180
|
-
|
|
|
181
|
-
| `
|
|
182
|
-
| `
|
|
183
|
-
| `
|
|
184
|
-
| `
|
|
185
|
-
| `
|
|
186
|
-
|
|
|
187
|
-
| `[field][operator]` | MongoDB operator filter | `?price[gte]=500` |
|
|
176
|
+
| Parameter | Example | Description |
|
|
177
|
+
| ----------- | ------------------------- | ------------------------------------------------- |
|
|
178
|
+
| `page` | `?page=3` | Page number (default: `1`, min: `1`) |
|
|
179
|
+
| `limit` | `?limit=25` | Documents per page (default: `10`, min: `1`) |
|
|
180
|
+
| `sort` | `?sort=-createdAt,name` | Sort fields; prefix `-` for descending |
|
|
181
|
+
| `fields` | `?fields=name,email` | Comma-separated fields to include in the response |
|
|
182
|
+
| `q` | `?q=john` | Global search term (used by `.globalFilter()`) |
|
|
183
|
+
| _(any key)_ | `?role=admin&age[gte]=18` | Field-level filters processed by `.filter()` |
|
|
188
184
|
|
|
189
185
|
---
|
|
190
186
|
|
|
191
|
-
##
|
|
187
|
+
## Full Example (Express)
|
|
192
188
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
189
|
+
```ts
|
|
190
|
+
import { Request, Response } from 'express';
|
|
191
|
+
import QueryFind from 'mongoose-query-find';
|
|
192
|
+
import UserModel from '../models/user';
|
|
197
193
|
|
|
198
|
-
const
|
|
199
|
-
.
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
194
|
+
export const getUsers = async (req: Request, res: Response) => {
|
|
195
|
+
const result = await new QueryFind(UserModel.find(), req.query)
|
|
196
|
+
.filter()
|
|
197
|
+
.globalFilter(['name', 'email', 'username'])
|
|
198
|
+
.sort()
|
|
199
|
+
.limitFields('-password -__v')
|
|
200
|
+
.paginate();
|
|
204
201
|
|
|
205
|
-
|
|
202
|
+
res.json({
|
|
203
|
+
status: 'success',
|
|
204
|
+
...result,
|
|
205
|
+
});
|
|
206
|
+
};
|
|
206
207
|
```
|
|
207
208
|
|
|
208
|
-
|
|
209
|
+
**Example requests:**
|
|
209
210
|
|
|
210
|
-
```
|
|
211
|
-
|
|
212
|
-
|
|
211
|
+
```bash
|
|
212
|
+
# Page 2, 15 per page, only active admins sorted by name
|
|
213
|
+
GET /users?page=2&limit=15&role=admin&isActive=true&sort=name
|
|
214
|
+
|
|
215
|
+
# Search "alice" across name, email, and username
|
|
216
|
+
GET /users?q=alice
|
|
213
217
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
218
|
+
# Users older than 25, return only name and email
|
|
219
|
+
GET /users?age[gt]=25&fields=name,email
|
|
220
|
+
|
|
221
|
+
# Combined: search + filter + sort + pagination
|
|
222
|
+
GET /users?q=john&role=editor&sort=-createdAt&page=1&limit=5
|
|
217
223
|
```
|
|
218
224
|
|
|
219
|
-
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## TypeScript Types
|
|
228
|
+
|
|
229
|
+
Both types are exported and available for use in your own code:
|
|
220
230
|
|
|
231
|
+
```ts
|
|
232
|
+
import QueryFind, { QueryParams, PaginatedResult } from 'mongoose-query-find';
|
|
221
233
|
```
|
|
222
|
-
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
interface QueryParams {
|
|
237
|
+
page?: string;
|
|
238
|
+
limit?: string;
|
|
239
|
+
sort?: string;
|
|
240
|
+
fields?: string;
|
|
241
|
+
q?: string;
|
|
242
|
+
[key: string]: unknown;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
interface PaginatedResult<T> {
|
|
246
|
+
data: T[];
|
|
247
|
+
total: number;
|
|
248
|
+
page: number;
|
|
249
|
+
totalPages: number;
|
|
250
|
+
limit: number;
|
|
251
|
+
}
|
|
223
252
|
```
|
|
224
253
|
|
|
225
|
-
|
|
254
|
+
---
|
|
255
|
+
|
|
256
|
+
## Links
|
|
257
|
+
|
|
258
|
+
- [npm](https://www.npmjs.com/package/mongoose-query-find)
|
|
259
|
+
- [GitHub](https://github.com/jsdev-robin/mongoose-query-find)
|
|
260
|
+
- [Issues](https://github.com/jsdev-robin/mongoose-query-find/issues)
|
|
226
261
|
|
|
227
262
|
---
|
|
228
263
|
|
|
229
264
|
## License
|
|
230
265
|
|
|
231
|
-
|
|
266
|
+
ISC © [jsdev.robin@gmail.com](mailto:jsdev.robin@gmail.com)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,21 +1,74 @@
|
|
|
1
|
-
import {
|
|
2
|
-
interface QueryParams {
|
|
1
|
+
import { Model, Query } from 'mongoose';
|
|
2
|
+
export interface QueryParams {
|
|
3
3
|
page?: string;
|
|
4
4
|
limit?: string;
|
|
5
5
|
sort?: string;
|
|
6
6
|
fields?: string;
|
|
7
|
-
|
|
7
|
+
q?: string;
|
|
8
|
+
[key: string]: unknown;
|
|
8
9
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
export interface PaginatedResult<T> {
|
|
11
|
+
data: T[];
|
|
12
|
+
total: number;
|
|
13
|
+
page: number;
|
|
14
|
+
totalPages: number;
|
|
15
|
+
limit: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
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).
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* const result = await new QueryFind(Model.find(), req.query)
|
|
24
|
+
* .filter()
|
|
25
|
+
* .globalFilter(['name', 'email'])
|
|
26
|
+
* .sort()
|
|
27
|
+
* .limitFields('-__v')
|
|
28
|
+
* .paginate();
|
|
29
|
+
*/
|
|
30
|
+
declare class QueryFind<TRawDocType, TModelType extends Model<TRawDocType> = Model<TRawDocType>> {
|
|
31
|
+
private readonly model;
|
|
32
|
+
private readonly queryString;
|
|
33
|
+
/** Accumulated Mongoose filter (populated by `filter()` and `globalFilter()`). */
|
|
34
|
+
private filterQuery;
|
|
35
|
+
/** Sort order applied in `paginate()`. */
|
|
36
|
+
private sortQuery;
|
|
37
|
+
/** Projection string applied in `paginate()`. */
|
|
38
|
+
private selectQuery;
|
|
39
|
+
constructor(query: Query<TRawDocType[], TRawDocType>, queryString: QueryParams);
|
|
40
|
+
/** Parse the URL query string into a Mongoose filter. */
|
|
13
41
|
filter(): this;
|
|
42
|
+
/**
|
|
43
|
+
* Add a case-insensitive `$or` regex search across the supplied fields
|
|
44
|
+
* when the query string contains a `q` parameter.
|
|
45
|
+
*/
|
|
14
46
|
globalFilter(fields: string[]): this;
|
|
47
|
+
/**
|
|
48
|
+
* Configure sort order from the `sort` query param.
|
|
49
|
+
* Falls back to `{ createdAt: -1 }` when the param is absent.
|
|
50
|
+
*/
|
|
15
51
|
sort(): this;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
52
|
+
/**
|
|
53
|
+
* Configure field projection.
|
|
54
|
+
* Uses the `fields` query param when present, otherwise falls back to
|
|
55
|
+
* `defaultFields`.
|
|
56
|
+
*
|
|
57
|
+
* @param defaultFields - A space- or comma-separated projection string,
|
|
58
|
+
* e.g. `'-password -__v'`.
|
|
59
|
+
*/
|
|
60
|
+
limitFields(defaultFields: string): this;
|
|
61
|
+
/**
|
|
62
|
+
* Execute the query and return a paginated result.
|
|
63
|
+
*
|
|
64
|
+
* Two database round-trips are made:
|
|
65
|
+
* 1. `countDocuments` with the current filter — O(index scan).
|
|
66
|
+
* 2. `find` with filter, sort, skip, limit, and projection.
|
|
67
|
+
*
|
|
68
|
+
* If the requested page exceeds `totalPages` (e.g. after a deletion),
|
|
69
|
+
* page 1 is returned instead so the caller always receives valid data.
|
|
70
|
+
*/
|
|
71
|
+
paginate(): Promise<PaginatedResult<TRawDocType>>;
|
|
19
72
|
}
|
|
20
73
|
export default QueryFind;
|
|
21
74
|
//# 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,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,KAAK,EAAe,MAAM,UAAU,CAAC;AAIrD,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;AAoGD;;;;;;;;;;;;GAYG;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,CAAgC;IAEnD,0CAA0C;IAC1C,OAAO,CAAC,SAAS,CAA6C;IAE9D,iDAAiD;IACjD,OAAO,CAAC,WAAW,CAAuB;gBAGxC,KAAK,EAAE,KAAK,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,EACxC,WAAW,EAAE,WAAW;IAQ1B,yDAAyD;IACzD,MAAM,IAAI,IAAI;IASd;;;OAGG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI;IAUpC;;;OAGG;IACH,IAAI,IAAI,IAAI;IAOZ;;;;;;;OAOG;IACH,WAAW,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI;IASxC;;;;;;;;;OASG;IACG,QAAQ,IAAI,OAAO,CAAC,eAAe,CAAC,WAAW,CAAC,CAAC;CAgCxD;AAED,eAAe,SAAS,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,79 +1,184 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
// Reserved keys stripped before building the filter
|
|
4
|
+
const RESERVED_KEYS = ['page', 'sort', 'limit', 'fields', 'q'];
|
|
5
|
+
// MongoDB comparison operators that need a `$` prefix
|
|
6
|
+
const MONGO_OPERATORS_RE = /\b(eq|ne|gt|gte|lt|lte|in|nin)\b/g;
|
|
7
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
8
|
+
/**
|
|
9
|
+
* Recursively keep only plain, JSON-serializable values (string, number,
|
|
10
|
+
* boolean, null, plain object, array). Drops anything that is a class
|
|
11
|
+
* instance, function, symbol, or undefined — which prevents circular-
|
|
12
|
+
* reference errors when req.query accidentally contains Mongoose/Express
|
|
13
|
+
* internal objects.
|
|
14
|
+
*/
|
|
15
|
+
function sanitize(value) {
|
|
16
|
+
if (value === null ||
|
|
17
|
+
typeof value === 'string' ||
|
|
18
|
+
typeof value === 'number' ||
|
|
19
|
+
typeof value === 'boolean') {
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
if (Array.isArray(value)) {
|
|
23
|
+
return value.map(sanitize).filter((v) => v !== undefined);
|
|
24
|
+
}
|
|
25
|
+
if (typeof value === 'object' &&
|
|
26
|
+
Object.getPrototypeOf(value) === Object.prototype) {
|
|
27
|
+
const result = {};
|
|
28
|
+
for (const [k, v] of Object.entries(value)) {
|
|
29
|
+
const sanitized = sanitize(v);
|
|
30
|
+
if (sanitized !== undefined) {
|
|
31
|
+
result[k] = sanitized;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
// Drop class instances, functions, symbols, undefined, etc.
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Coerce plain string booleans to real booleans so filters like
|
|
41
|
+
* `?isActive=true` work correctly against boolean schema fields.
|
|
42
|
+
*/
|
|
43
|
+
function coerceBooleans(obj) {
|
|
44
|
+
return Object.fromEntries(Object.entries(obj).map(([k, v]) => {
|
|
45
|
+
if (v === 'true')
|
|
46
|
+
return [k, true];
|
|
47
|
+
if (v === 'false')
|
|
48
|
+
return [k, false];
|
|
49
|
+
return [k, v];
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Parse the raw query string into a Mongoose-compatible filter object.
|
|
54
|
+
* Strips reserved keys, sanitizes all values to plain JSON-safe types,
|
|
55
|
+
* and rewrites bare operator names (gt → $gt, etc.).
|
|
56
|
+
*/
|
|
57
|
+
function buildFilterFromQueryString(raw) {
|
|
58
|
+
// Strip reserved keys first
|
|
59
|
+
const stripped = Object.fromEntries(Object.entries(raw).filter(([k]) => !RESERVED_KEYS.includes(k)));
|
|
60
|
+
// Sanitize to plain values only — prevents circular JSON errors
|
|
61
|
+
const safe = sanitize(stripped);
|
|
62
|
+
// Rewrite bare operator names to MongoDB $ operators
|
|
63
|
+
const withOperators = JSON.parse(JSON.stringify(safe).replace(MONGO_OPERATORS_RE, (m) => `$${m}`));
|
|
64
|
+
return coerceBooleans(withOperators);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Parse a comma-separated sort string (e.g. `-createdAt,name`) into a
|
|
68
|
+
* `{ field: 1 | -1 }` map.
|
|
69
|
+
*/
|
|
70
|
+
function parseSortString(sort) {
|
|
71
|
+
return Object.fromEntries(sort.split(',').map((f) => (f.startsWith('-') ? [f.slice(1), -1] : [f, 1])));
|
|
72
|
+
}
|
|
73
|
+
// ─── QueryFind ────────────────────────────────────────────────────────────────
|
|
74
|
+
/**
|
|
75
|
+
* Fluent query builder that progressively refines a Mongoose query,
|
|
76
|
+
* then paginates the result using two native `countDocuments` + `find` calls
|
|
77
|
+
* (no aggregation pipeline required).
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* const result = await new QueryFind(Model.find(), req.query)
|
|
81
|
+
* .filter()
|
|
82
|
+
* .globalFilter(['name', 'email'])
|
|
83
|
+
* .sort()
|
|
84
|
+
* .limitFields('-__v')
|
|
85
|
+
* .paginate();
|
|
86
|
+
*/
|
|
3
87
|
class QueryFind {
|
|
4
88
|
constructor(query, queryString) {
|
|
5
|
-
|
|
89
|
+
/** Accumulated Mongoose filter (populated by `filter()` and `globalFilter()`). */
|
|
90
|
+
this.filterQuery = {};
|
|
91
|
+
/** Sort order applied in `paginate()`. */
|
|
92
|
+
this.sortQuery = { createdAt: -1 };
|
|
93
|
+
/** Projection string applied in `paginate()`. */
|
|
94
|
+
this.selectQuery = null;
|
|
95
|
+
this.model = query.model;
|
|
6
96
|
this.queryString = queryString;
|
|
7
97
|
}
|
|
98
|
+
// ── Builder methods ─────────────────────────────────────────────────────────
|
|
99
|
+
/** Parse the URL query string into a Mongoose filter. */
|
|
8
100
|
filter() {
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const parsedQuery = JSON.parse(queryStr);
|
|
15
|
-
Object.keys(parsedQuery).forEach((key) => {
|
|
16
|
-
const val = parsedQuery[key];
|
|
17
|
-
if (val === 'true') {
|
|
18
|
-
parsedQuery[key] = true;
|
|
19
|
-
}
|
|
20
|
-
else if (val === 'false') {
|
|
21
|
-
parsedQuery[key] = false;
|
|
22
|
-
}
|
|
23
|
-
else if (typeof val === 'string') {
|
|
24
|
-
parsedQuery[key] = { $regex: val, $options: 'i' };
|
|
25
|
-
}
|
|
26
|
-
});
|
|
27
|
-
this.query = this.query.find(parsedQuery);
|
|
101
|
+
const parsed = buildFilterFromQueryString(this.queryString);
|
|
102
|
+
this.filterQuery = {
|
|
103
|
+
...this.filterQuery,
|
|
104
|
+
...parsed,
|
|
105
|
+
};
|
|
28
106
|
return this;
|
|
29
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Add a case-insensitive `$or` regex search across the supplied fields
|
|
110
|
+
* when the query string contains a `q` parameter.
|
|
111
|
+
*/
|
|
30
112
|
globalFilter(fields) {
|
|
31
113
|
const search = this.queryString.q;
|
|
32
114
|
if (search && fields.length > 0) {
|
|
33
|
-
|
|
115
|
+
this.filterQuery.$or = fields.map((field) => ({
|
|
34
116
|
[field]: { $regex: search, $options: 'i' },
|
|
35
117
|
}));
|
|
36
|
-
this.query = this.query.model.find();
|
|
37
|
-
this.query = this.query.find({ $or: orConditions });
|
|
38
118
|
}
|
|
39
119
|
return this;
|
|
40
120
|
}
|
|
121
|
+
/**
|
|
122
|
+
* Configure sort order from the `sort` query param.
|
|
123
|
+
* Falls back to `{ createdAt: -1 }` when the param is absent.
|
|
124
|
+
*/
|
|
41
125
|
sort() {
|
|
42
126
|
if (this.queryString.sort) {
|
|
43
|
-
|
|
44
|
-
this.query = this.query.sort(sortBy);
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
this.query = this.query.sort('-createdAt');
|
|
127
|
+
this.sortQuery = parseSortString(this.queryString.sort);
|
|
48
128
|
}
|
|
49
129
|
return this;
|
|
50
130
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const limit = parseInt(this.queryString.limit || '100', 10);
|
|
64
|
-
const skip = (page - 1) * limit;
|
|
65
|
-
this.query = this.query.skip(skip).limit(limit);
|
|
131
|
+
/**
|
|
132
|
+
* Configure field projection.
|
|
133
|
+
* Uses the `fields` query param when present, otherwise falls back to
|
|
134
|
+
* `defaultFields`.
|
|
135
|
+
*
|
|
136
|
+
* @param defaultFields - A space- or comma-separated projection string,
|
|
137
|
+
* e.g. `'-password -__v'`.
|
|
138
|
+
*/
|
|
139
|
+
limitFields(defaultFields) {
|
|
140
|
+
this.selectQuery = this.queryString.fields
|
|
141
|
+
? this.queryString.fields.split(',').join(' ')
|
|
142
|
+
: defaultFields;
|
|
66
143
|
return this;
|
|
67
144
|
}
|
|
68
|
-
|
|
69
|
-
|
|
145
|
+
// ── Terminal method ─────────────────────────────────────────────────────────
|
|
146
|
+
/**
|
|
147
|
+
* Execute the query and return a paginated result.
|
|
148
|
+
*
|
|
149
|
+
* Two database round-trips are made:
|
|
150
|
+
* 1. `countDocuments` with the current filter — O(index scan).
|
|
151
|
+
* 2. `find` with filter, sort, skip, limit, and projection.
|
|
152
|
+
*
|
|
153
|
+
* If the requested page exceeds `totalPages` (e.g. after a deletion),
|
|
154
|
+
* page 1 is returned instead so the caller always receives valid data.
|
|
155
|
+
*/
|
|
156
|
+
async paginate() {
|
|
157
|
+
const page = Math.max(parseInt(this.queryString.page ?? '1', 10), 1);
|
|
158
|
+
const limit = Math.max(parseInt(this.queryString.limit ?? '10', 10), 1);
|
|
159
|
+
// ── 1. Count matching documents ────────────────────────────────────────
|
|
160
|
+
const total = await this.model.countDocuments(this.filterQuery);
|
|
161
|
+
const totalPages = Math.ceil(total / limit) || 1;
|
|
162
|
+
const safePage = page > totalPages ? 1 : page;
|
|
163
|
+
const skip = (safePage - 1) * limit;
|
|
164
|
+
// ── 2. Fetch the page ──────────────────────────────────────────────────
|
|
165
|
+
const findQuery = this.model
|
|
166
|
+
.find(this.filterQuery)
|
|
167
|
+
.sort(this.sortQuery)
|
|
168
|
+
.skip(skip)
|
|
169
|
+
.limit(limit);
|
|
170
|
+
if (this.selectQuery) {
|
|
171
|
+
findQuery.select(this.selectQuery);
|
|
172
|
+
}
|
|
173
|
+
const data = await findQuery.exec();
|
|
174
|
+
return {
|
|
175
|
+
data: data,
|
|
176
|
+
total,
|
|
177
|
+
page: safePage,
|
|
178
|
+
totalPages,
|
|
179
|
+
limit,
|
|
180
|
+
};
|
|
70
181
|
}
|
|
71
182
|
}
|
|
72
183
|
exports.default = QueryFind;
|
|
73
|
-
// Ref
|
|
74
|
-
// new QueryFind(collection.find(), query)
|
|
75
|
-
// .filter()
|
|
76
|
-
// .sort()
|
|
77
|
-
// .limitFields()
|
|
78
|
-
// .paginate();
|
|
79
184
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAqBA,oDAAoD;AACpD,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,CAAU,CAAC;AAGxE,sDAAsD;AACtD,MAAM,kBAAkB,GAAG,mCAAmC,CAAC;AAE/D,iFAAiF;AAEjF;;;;;;GAMG;AACH,SAAS,QAAQ,CAAC,KAAc;IAC9B,IACE,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAO,KAAK,KAAK,SAAS,EAC1B;QACA,OAAO,KAAK,CAAC;KACd;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QACxB,OAAO,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;KAC3D;IAED,IACE,OAAO,KAAK,KAAK,QAAQ;QACz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