mongoose-query-find 1.4.0 → 1.5.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
@@ -1,41 +1,10 @@
1
1
  # mongoose-query-find
2
2
 
3
- > A TypeScript utility for Mongoose that simplifies building dynamic, chainable queries with filtering, global search, sorting, field selection, and pagination.
3
+ [![npm version](https://img.shields.io/npm/v/mongoose-query-find)](https://www.npmjs.com/package/mongoose-query-find)
4
+ [![license](https://img.shields.io/npm/l/mongoose-query-find)](https://github.com/jsdev-robin/mongoose-query-find/blob/main/LICENSE)
5
+ [![mongoose peer](https://img.shields.io/badge/mongoose-%5E8%20%7C%7C%20%5E9-brightgreen)](https://mongoosejs.com)
4
6
 
5
- [![npm version](https://img.shields.io/npm/v/mongoose-query-find.svg)](https://www.npmjs.com/package/mongoose-query-find)
6
- [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)
7
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.2-blue)](https://www.typescriptlang.org/)
8
- [![mongoose](https://img.shields.io/badge/mongoose-%5E8%20%7C%7C%20%5E9-green)](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
- > **Peer dependency:** Requires `mongoose@^8` or `mongoose@^9`.
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
- ```typescript
31
+ ```ts
55
32
  import QueryFind from 'mongoose-query-find';
56
- import { Request, Response } from 'express';
57
- import Product from './models/Product';
33
+ import UserModel from './models/user';
58
34
 
59
- export const getProducts = async (req: Request, res: Response) => {
60
- const features = new QueryFind(Product.find(), req.query)
61
- .filter()
62
- .sort()
63
- .limitFields()
64
- .paginate();
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
- const products = await features.exec();
43
+ `result` will look like:
67
44
 
68
- res.json({ results: products.length, data: products });
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
- ## API Reference
57
+ ## Constructor
75
58
 
76
- ### `new QueryFind(query, queryString)`
59
+ ```ts
60
+ new QueryFind(query, queryString);
61
+ ```
77
62
 
78
- | Parameter | Type | Description |
79
- | ------------- | --------------- | --------------------------------------------- |
80
- | `query` | `Query<T[], T>` | A Mongoose query object (e.g. `Model.find()`) |
81
- | `queryString` | `QueryParams` | Parsed query string from the request |
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
- ### `filter()`
70
+ ## Builder Methods
71
+
72
+ All builder methods return `this`, so they are fully chainable in any order.
73
+
74
+ ### `.filter()`
86
75
 
87
- Applies field-level filtering from the query string. Automatically prepends `$` to MongoDB operators and wraps plain string values in a case-insensitive regex.
76
+ Parses the URL query string into a Mongoose filter. Automatically:
88
77
 
89
- **Supported operators:** `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `regex`, `exists`, `all`, `size`, `elemMatch`, `type`, `mod`, `not`, `and`, `or`, `nor`, `text`, `where`, `geoWithin`, `geoIntersects`, `near`, `nearSphere`, `expr`, `jsonSchema`, `bitsAllClear`, `bitsAllSet`, `bitsAnyClear`, `bitsAnySet`, `rand`
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
- **Example URL:**
82
+ **Supported operators:** `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`
92
83
 
93
84
  ```
94
- GET /api/products?price[gte]=100&category=electronics
85
+ GET /users?age[gte]=18&isActive=true&role=admin
95
86
  ```
96
87
 
97
- ---
98
-
99
- ### `globalFilter(fields)`
88
+ ```ts
89
+ .filter()
90
+ // → { age: { $gte: 18 }, isActive: true, role: 'admin' }
91
+ ```
100
92
 
101
- Performs a global search across the specified fields using the `q` query parameter with case-insensitive regex.
93
+ ---
102
94
 
103
- | Parameter | Type | Description |
104
- | --------- | ---------- | ------------------------------------- |
105
- | `fields` | `string[]` | Array of field names to search across |
95
+ ### `.globalFilter(fields: string[])`
106
96
 
107
- **Example:**
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
- GET /api/products?q=wireless+headphones
102
+
103
+ ```ts
104
+ .globalFilter(['name', 'email'])
105
+ // → { $or: [{ name: /john/i }, { email: /john/i }] }
119
106
  ```
120
107
 
121
108
  ---
122
109
 
123
- ### `sort()`
110
+ ### `.sort()`
124
111
 
125
- Sorts results based on the `sort` query parameter. Multiple fields can be comma-separated. Defaults to `-createdAt` (newest first) if no sort is specified.
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 /api/products?sort=price # ascending by price
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
- ### `limitFields()`
125
+ ---
138
126
 
139
- Selects specific fields to include or exclude using the `fields` query parameter. Defaults to excluding `__v`.
127
+ ### `.limitFields(defaultFields: string)`
140
128
 
141
- **Example URLs:**
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 /api/products?fields=name,price,category # include only these fields
145
- GET /api/products?fields=-description,-__v # exclude these fields
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
- ### `paginate()`
143
+ ## Terminal Method
151
144
 
152
- Applies skip/limit pagination using `page` and `limit` query parameters.
145
+ ### `.paginate()`
153
146
 
154
- | Parameter | Default | Description |
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
- **Example URL:**
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 /api/products?page=2&limit=20
153
+ GET /users?page=2&limit=20
163
154
  ```
164
155
 
165
- ---
156
+ **Returns:**
166
157
 
167
- ### `exec()`
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
- Executes the built query and returns a `Promise<T[]>`.
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
- ```typescript
172
- const results = await features.exec();
173
- ```
170
+ **Defaults:** `page=1`, `limit=10`
174
171
 
175
172
  ---
176
173
 
177
- ## Query String Parameters
174
+ ## Query Parameter Reference
178
175
 
179
- | Parameter | Description | Example |
180
- | ------------------- | ------------------------------- | -------------------- |
181
- | `q` | Global search term | `?q=laptop` |
182
- | `sort` | Comma-separated sort fields | `?sort=-price,name` |
183
- | `fields` | Comma-separated field selection | `?fields=name,price` |
184
- | `page` | Page number for pagination | `?page=3` |
185
- | `limit` | Results per page | `?limit=25` |
186
- | `[field]` | Filter by any document field | `?brand=apple` |
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
- ## Examples
187
+ ## Full Example (Express)
192
188
 
193
- ### Combined Usage
194
-
195
- ```typescript
196
- // GET /api/products?q=phone&price[gte]=200&sort=-createdAt&fields=name,price&page=1&limit=10
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 features = new QueryFind(Product.find(), req.query)
199
- .globalFilter(['name', 'description'])
200
- .filter()
201
- .sort()
202
- .limitFields()
203
- .paginate();
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
- const products = await features.exec();
202
+ res.json({
203
+ status: 'success',
204
+ ...result,
205
+ });
206
+ };
206
207
  ```
207
208
 
208
- ### Filtering with Operators
209
+ **Example requests:**
209
210
 
210
- ```
211
- GET /api/products?price[gte]=100&price[lte]=500&stock[gt]=0
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
- ```typescript
215
- // Equivalent to:
216
- Product.find({ price: { $gte: 100, $lte: 500 }, stock: { $gt: 0 } });
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
- ### Pagination
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
- GET /api/products?page=2&limit=15
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
- Skips the first 15 results and returns the next 15.
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
- [ISC](https://opensource.org/licenses/ISC) © [jsdev.robin@gmail.com](mailto:jsdev.robin@gmail.com)
266
+ ISC © [jsdev.robin@gmail.com](mailto:jsdev.robin@gmail.com)
package/dist/index.d.ts CHANGED
@@ -1,21 +1,74 @@
1
- import { Document, Query } from 'mongoose';
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
- [key: string]: string | number | unknown;
7
+ q?: string;
8
+ [key: string]: unknown;
8
9
  }
9
- declare class QueryFind<T extends Document> {
10
- query: Query<T[], T>;
11
- queryString: QueryParams;
12
- constructor(query: Query<T[], T>, queryString: QueryParams);
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
- limitFields(fields: string): this;
17
- paginate(): this;
18
- exec(): Promise<T[]>;
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
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAE3C,UAAU,WAAW;IACnB,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,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;CAC1C;AAED,cAAM,SAAS,CAAC,CAAC,SAAS,QAAQ;IAChC,KAAK,EAAE,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IACrB,WAAW,EAAE,WAAW,CAAC;gBAEb,KAAK,EAAE,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,WAAW,EAAE,WAAW;IAK1D,MAAM,IAAI,IAAI;IA6Bd,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI;IAapC,IAAI,IAAI,IAAI;IAWZ,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAWjC,QAAQ,IAAI,IAAI;IAUV,IAAI,IAAI,OAAO,CAAC,CAAC,EAAE,CAAC;CAG3B;AAED,eAAe,SAAS,CAAC"}
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;AAuDD;;;;;;;;;;;;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,148 @@
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
+ * Coerce plain string booleans to real booleans so filters like
10
+ * `?isActive=true` work correctly against boolean schema fields.
11
+ */
12
+ function coerceBooleans(obj) {
13
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => {
14
+ if (v === 'true')
15
+ return [k, true];
16
+ if (v === 'false')
17
+ return [k, false];
18
+ return [k, v];
19
+ }));
20
+ }
21
+ /**
22
+ * Parse the raw query string into a Mongoose-compatible filter object.
23
+ * Strips reserved keys and rewrites bare operator names (gt → $gt, etc.).
24
+ */
25
+ function buildFilterFromQueryString(raw) {
26
+ const queryObj = Object.fromEntries(Object.entries(raw).filter(([k]) => !RESERVED_KEYS.includes(k)));
27
+ const withOperators = JSON.parse(JSON.stringify(queryObj).replace(MONGO_OPERATORS_RE, (m) => `$${m}`));
28
+ return coerceBooleans(withOperators);
29
+ }
30
+ /**
31
+ * Parse a comma-separated sort string (e.g. `-createdAt,name`) into a
32
+ * `{ field: 1 | -1 }` map.
33
+ */
34
+ function parseSortString(sort) {
35
+ return Object.fromEntries(sort.split(',').map((f) => (f.startsWith('-') ? [f.slice(1), -1] : [f, 1])));
36
+ }
37
+ // ─── QueryFind ────────────────────────────────────────────────────────────────
38
+ /**
39
+ * Fluent query builder that progressively refines a Mongoose query,
40
+ * then paginates the result using two native `countDocuments` + `find` calls
41
+ * (no aggregation pipeline required).
42
+ *
43
+ * @example
44
+ * const result = await new QueryFind(Model.find(), req.query)
45
+ * .filter()
46
+ * .globalFilter(['name', 'email'])
47
+ * .sort()
48
+ * .limitFields('-__v')
49
+ * .paginate();
50
+ */
3
51
  class QueryFind {
4
52
  constructor(query, queryString) {
5
- this.query = query;
53
+ /** Accumulated Mongoose filter (populated by `filter()` and `globalFilter()`). */
54
+ this.filterQuery = {};
55
+ /** Sort order applied in `paginate()`. */
56
+ this.sortQuery = { createdAt: -1 };
57
+ /** Projection string applied in `paginate()`. */
58
+ this.selectQuery = null;
59
+ this.model = query.model;
6
60
  this.queryString = queryString;
7
61
  }
62
+ // ── Builder methods ─────────────────────────────────────────────────────────
63
+ /** Parse the URL query string into a Mongoose filter. */
8
64
  filter() {
9
- const queryObj = { ...this.queryString };
10
- const excludedFields = ['page', 'sort', 'limit', 'fields'];
11
- excludedFields.forEach((el) => delete queryObj[el]);
12
- let queryStr = JSON.stringify(queryObj);
13
- queryStr = queryStr.replace(/\b(eq|ne|gt|gte|lt|lte|in|nin|regex|exists|all|size|elemMatch|type|mod|not|and|or|nor|text|where|geoWithin|geoIntersects|near|nearSphere|expr|jsonSchema|bitsAllClear|bitsAllSet|bitsAnyClear|bitsAnySet|rand)\b/g, (match) => `$${match}`);
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);
65
+ const parsed = buildFilterFromQueryString(this.queryString);
66
+ this.filterQuery = {
67
+ ...this.filterQuery,
68
+ ...parsed,
69
+ };
28
70
  return this;
29
71
  }
72
+ /**
73
+ * Add a case-insensitive `$or` regex search across the supplied fields
74
+ * when the query string contains a `q` parameter.
75
+ */
30
76
  globalFilter(fields) {
31
77
  const search = this.queryString.q;
32
78
  if (search && fields.length > 0) {
33
- const orConditions = fields.map((field) => ({
79
+ this.filterQuery.$or = fields.map((field) => ({
34
80
  [field]: { $regex: search, $options: 'i' },
35
81
  }));
36
- this.query = this.query.model.find();
37
- this.query = this.query.find({ $or: orConditions });
38
82
  }
39
83
  return this;
40
84
  }
85
+ /**
86
+ * Configure sort order from the `sort` query param.
87
+ * Falls back to `{ createdAt: -1 }` when the param is absent.
88
+ */
41
89
  sort() {
42
90
  if (this.queryString.sort) {
43
- const sortBy = this.queryString.sort.split(',').join(' ');
44
- this.query = this.query.sort(sortBy);
45
- }
46
- else {
47
- this.query = this.query.sort('-createdAt');
91
+ this.sortQuery = parseSortString(this.queryString.sort);
48
92
  }
49
93
  return this;
50
94
  }
51
- limitFields(fields) {
52
- if (this.queryString.fields) {
53
- const selected = this.queryString.fields.split(',').join(' ');
54
- this.query = this.query.select(selected);
55
- }
56
- else {
57
- this.query = this.query.select(fields);
58
- }
59
- return this;
60
- }
61
- paginate() {
62
- const page = parseInt(this.queryString.page || '1', 10);
63
- const limit = parseInt(this.queryString.limit || '100', 10);
64
- const skip = (page - 1) * limit;
65
- this.query = this.query.skip(skip).limit(limit);
95
+ /**
96
+ * Configure field projection.
97
+ * Uses the `fields` query param when present, otherwise falls back to
98
+ * `defaultFields`.
99
+ *
100
+ * @param defaultFields - A space- or comma-separated projection string,
101
+ * e.g. `'-password -__v'`.
102
+ */
103
+ limitFields(defaultFields) {
104
+ this.selectQuery = this.queryString.fields
105
+ ? this.queryString.fields.split(',').join(' ')
106
+ : defaultFields;
66
107
  return this;
67
108
  }
68
- async exec() {
69
- return await this.query.exec();
109
+ // ── Terminal method ─────────────────────────────────────────────────────────
110
+ /**
111
+ * Execute the query and return a paginated result.
112
+ *
113
+ * Two database round-trips are made:
114
+ * 1. `countDocuments` with the current filter — O(index scan).
115
+ * 2. `find` with filter, sort, skip, limit, and projection.
116
+ *
117
+ * If the requested page exceeds `totalPages` (e.g. after a deletion),
118
+ * page 1 is returned instead so the caller always receives valid data.
119
+ */
120
+ async paginate() {
121
+ const page = Math.max(parseInt(this.queryString.page ?? '1', 10), 1);
122
+ const limit = Math.max(parseInt(this.queryString.limit ?? '10', 10), 1);
123
+ // ── 1. Count matching documents ────────────────────────────────────────
124
+ const total = await this.model.countDocuments(this.filterQuery);
125
+ const totalPages = Math.ceil(total / limit) || 1;
126
+ const safePage = page > totalPages ? 1 : page;
127
+ const skip = (safePage - 1) * limit;
128
+ // ── 2. Fetch the page ──────────────────────────────────────────────────
129
+ const findQuery = this.model
130
+ .find(this.filterQuery)
131
+ .sort(this.sortQuery)
132
+ .skip(skip)
133
+ .limit(limit);
134
+ if (this.selectQuery) {
135
+ findQuery.select(this.selectQuery);
136
+ }
137
+ const data = await findQuery.exec();
138
+ return {
139
+ data: data,
140
+ total,
141
+ page: safePage,
142
+ totalPages,
143
+ limit,
144
+ };
70
145
  }
71
146
  }
72
147
  exports.default = QueryFind;
73
- // Ref
74
- // new QueryFind(collection.find(), query)
75
- // .filter()
76
- // .sort()
77
- // .limitFields()
78
- // .paginate();
79
148
  //# 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":";;AAUA,MAAM,SAAS;IAIb,YAAY,KAAoB,EAAE,WAAwB;QACxD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAED,MAAM;QACJ,MAAM,QAAQ,GAA4B,EAAE,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QAClE,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC3D,cAAc,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QAEpD,IAAI,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAExC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CACzB,mNAAmN,EACnN,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CACvB,CAAC;QAEF,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAEzC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YACv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