@r5v/mongoose-paginate 1.0.14 → 1.0.16

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
@@ -139,7 +139,7 @@ GET /api/books?$lean=true
139
139
  | staticPostFilter | Mongo Filter Object | create a filter on the pipeline that is added after all the pipeline stages. this cannot be overwritten by params | AggregationPagingQuery | | {} |
140
140
  | staticFilter | Mongo Filter Object | create a filter on the pipeline that is added before all the pipeline stages. on find requests, this is added to the filter object. this cannot be overwritten by params | AggregationPagingQuery | | {} |
141
141
  | pipeline | MongoPipelineStage[] | pipeline request object. if the first item in pipeline stage is a $match or another required first stage operator. it will be placed before all other modifiers | AggregationPagingQuery | true | [] |
142
- | removeProtected \(REMOVED\) | boolean | auto remove protected (select: false) for root Model | AggregationPagingQuery | | false |
142
+ | removeProtected | boolean | **EXPERIMENTAL** - auto remove protected fields (those with `select: false` in schema) from aggregation results. Use with caution and test thoroughly in your environment | AggregationPagingQuery | | false |
143
143
 
144
144
  ## Utilities
145
145
 
@@ -307,8 +307,9 @@ $ yarn run start
307
307
  9. Apply pagination (`$skip`, `$limit`) and options
308
308
 
309
309
 
310
- ## NOTES
311
- 1. removeProtected removed from aggregation query due to inconsistent results after publication
310
+ ### 1.0.15
311
+ - **Re-enabled `removeProtected` option** for `AggregationPagingQuery` (EXPERIMENTAL) - Automatically excludes fields marked with `select: false` in your schema (e.g., passwords, secret keys) from aggregation results. Use with caution and test thoroughly in your environment.
312
+ - Uses refactored `findProtectedPaths` utility which safely traverses schemas without JSON serialization
312
313
 
313
314
  ### 1.0.14
314
315
  - Added proper TypeScript package exports with subpaths (`/utils`, `/types`)
package/dist/README.md ADDED
@@ -0,0 +1,348 @@
1
+
2
+
3
+ @r5v/mongoose-pagination is a powerful yet lightweight utility that bridges the gap between HTTP query parameters and MongoDB queries. It provides an intuitive wrapper around Mongoose models, allowing you to easily transform Express request objects into sophisticated database queries with pagination, filtering, and sorting capabilities.
4
+
5
+ Simple, Fast, Efficient
6
+
7
+ This project was designed to accomodate more than 80% of your daily workflow to remove the overhead of boilerplate code in handling each endpoint and keeping queries and query params simple. We didn't want you to have to learn a new language to use this product
8
+
9
+ ## Basic Usage
10
+
11
+ ### PagingQuery
12
+ ```typescript
13
+ // userController.ts
14
+ import {PagingQuery} from '@r5v/mongoose-paginate'
15
+ import {UserModel} from "./models"
16
+
17
+ const getUsersController: RequestHandler = async (res, res) => {
18
+
19
+ const query = new PagingQuery(req, User, {})
20
+ const users = await query.exec()
21
+
22
+ res.send(users)
23
+ }
24
+ ```
25
+
26
+ #### Results
27
+
28
+ ```
29
+ {
30
+ totalRows: 0,
31
+ rows: 0,
32
+ limit: 25,
33
+ skip: 0,
34
+ items: [ <UserObject>]
35
+ }
36
+ ```
37
+
38
+ ### AggregationPagingQuery
39
+ ```typescript
40
+ // userController.ts
41
+ import {AggregationPagingQuery} from '@r5v/mongoose-paginate'
42
+ import {UserModel} from "./models"
43
+
44
+ const getUsersController: RequestHandler = async (res, res) => {
45
+
46
+ const query = new AggregationPagingQuery(req, User, {
47
+ pipeline: [ {$match:{name:/^Steve/}}]
48
+ })
49
+ const users = await query.exec()
50
+
51
+ res.send(users)
52
+ }
53
+ ```
54
+
55
+ #### Results
56
+
57
+ ```
58
+ {
59
+ totalRows: 0,
60
+ rows: 0,
61
+ limit: 25,
62
+ skip: 0,
63
+ items: [ <UserObject>]
64
+ }
65
+ ```
66
+
67
+ ### Definition
68
+
69
+ PagingQuery(Express.Request, mongoose.Model, options )
70
+
71
+ #### Query Parameters
72
+
73
+ | Name | Value | Description | Class Availability |
74
+ |:------------|:----------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|
75
+ | $filter | Mongo Filter Object | any json string can be passed in this parameter. be sure to turn on sanitizeFilter if you allow dynamic filters | PagingQuery, AggregationPagingQuery |
76
+ | $limit | number | limit the number of returned objects | PagingQuery, AggregationPagingQuery |
77
+ | $skip | number | skip to the next object on the request | PagingQuery, AggregationPagingQuery |
78
+ | $paging | 'false'\|0\|'no' | turn off paging, on by default | PagingQuery, AggregationPagingQuery |
79
+ | $populate | comma separated dot notation string \n books,publishers | using refs and virtuals, a dot notation string will populate the model using .populate. will deep populate and select using \"authors\[name\].books\[title\],publishers\[name\]" notation | PagingQuery |
80
+ | $select | comma separated dot notation string \n books,-_id \| -_id,-name,address.-address1 | using the select notation uses the mongoose name \| -name syntax to filter the output. use this in conjunction with the $populate query to filter keys \n ie books.title,books.publisher \| -name,books.-title | PagingQuery, AggregationPagingQuery |
81
+ | $lean | no value needed, this will return a lean query result | returns a lean result. does not require a value | PagingQuery |
82
+ | $sort | space separated mongoose sort string \n name -value | inserts sort into the query. In aggregation queries this will insert a sort after the existing pipeline | PagingQuery, AggregationPagingQuery |
83
+ | $preSort | comma separated dot notation string \n books,-_id \| -_id,-name,address.-address1 | in aggregate queries this will insert a sort object after the initial match in the pipeline. | AggregationPagingQuery |
84
+ | $count | comma separated dot notation string | this comma separate string will traverse the results and insert a new field with the $size of the selected key/value . this new name field will be appended with `_count` | AggregationPagingQuery |
85
+ | $postFilter | Any Json Object | creates and additional filter and in aggregation queries is appended to the end of the pipeline | AggregationPagingQuery |
86
+
87
+ #### Example URLs
88
+
89
+ ```bash
90
+ # Basic pagination
91
+ GET /api/books?$limit=10&$skip=20
92
+
93
+ # Filter by field (JSON format)
94
+ GET /api/books?$filter={"genre":"Horror"}
95
+
96
+ # Filter with operators
97
+ GET /api/books?$filter={"price.amount":{"$gte":20,"$lte":50}}
98
+
99
+ # Sort (space-separated: field direction)
100
+ GET /api/books?$sort=price.amount%20desc
101
+ GET /api/books?$sort=title%20asc,createdAt%20desc
102
+
103
+ # Select specific fields
104
+ GET /api/books?$select=title,isbn,price
105
+
106
+ # Populate references
107
+ GET /api/books?$populate=author,publisher
108
+
109
+ # Deep populate with field selection
110
+ GET /api/books?$populate=author[firstName,lastName],publisher[name]
111
+
112
+ # Aggregation with preSort (sorts before pipeline)
113
+ GET /api/books?$preSort=createdAt%20desc
114
+
115
+ # Aggregation with postFilter (filters on computed fields)
116
+ GET /api/books?$postFilter={"priceCategory":"expensive"}
117
+
118
+ # Count array fields
119
+ GET /api/books?$count=authors,tags
120
+ # Result includes: authors_count, tags_count
121
+
122
+ # Disable paging (returns array instead of paged object)
123
+ GET /api/books?$paging=false
124
+
125
+ # Lean query (returns plain objects)
126
+ GET /api/books?$lean=true
127
+ ```
128
+
129
+ #### Options
130
+
131
+ | Key | Value | Description | Class Availability | Required | Default |
132
+ |:----------------------------|:---------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------|:---------|:--------|
133
+ | disablePaging | boolean | disables paging and $paging param use | PagingQuery, AggregationPagingQuery | | false |
134
+ | disableFilter | boolean | disables the $filter param on req. | PagingQuery | | false |
135
+ | enableFilter | boolean | enables the $filter param on req for aggregation queries. | AggregationPagingQuery | | false |
136
+ | enablePreSort | boolean | enables the $preSort param on req for aggregation queries. | AggregationPagingQuery | | false |
137
+ | single | boolean | disables paging on the query. converts from .find query to .findOne() | PagingQuery | | false |
138
+ | enablePostFilter | boolean | enables the ability to create a dynamic filter per request using the $postFilter parameter | AggregationPagingQuery | | false |
139
+ | staticPostFilter | Mongo Filter Object | create a filter on the pipeline that is added after all the pipeline stages. this cannot be overwritten by params | AggregationPagingQuery | | {} |
140
+ | staticFilter | Mongo Filter Object | create a filter on the pipeline that is added before all the pipeline stages. on find requests, this is added to the filter object. this cannot be overwritten by params | AggregationPagingQuery | | {} |
141
+ | pipeline | MongoPipelineStage[] | pipeline request object. if the first item in pipeline stage is a $match or another required first stage operator. it will be placed before all other modifiers | AggregationPagingQuery | true | [] |
142
+ | removeProtected | boolean | **EXPERIMENTAL** - auto remove protected fields (those with `select: false` in schema) from aggregation results. Use with caution and test thoroughly in your environment | AggregationPagingQuery | | false |
143
+
144
+ ## Utilities
145
+
146
+ All utilities can be imported directly from the main package or from the `/utils` subpath:
147
+
148
+ ```typescript
149
+ // Direct import
150
+ import { buildPopulate, parseSortString, getPropertyFromDotNotation } from '@r5v/mongoose-paginate'
151
+
152
+ // Subpath import (all utilities)
153
+ import * as utils from '@r5v/mongoose-paginate/utils'
154
+ ```
155
+
156
+ ### Populate Utilities
157
+
158
+ | Name | Signature | Description |
159
+ |:-----|:----------|:------------|
160
+ | `buildPopulate` | `(pathString: string) => PopulateItem[]` | Creates a Mongoose populate object from dot notation string. Supports deep population with field selection using bracket notation: `"author[name].books[title],publisher[name]"` |
161
+
162
+ ```typescript
163
+ import { buildPopulate } from '@r5v/mongoose-paginate'
164
+
165
+ const populate = buildPopulate('author[name,email].books[title],publisher')
166
+ // Result: [
167
+ // { path: 'author', select: 'name email', populate: [{ path: 'books', select: 'title' }] },
168
+ // { path: 'publisher' }
169
+ // ]
170
+ ```
171
+
172
+ ### Sort Utilities
173
+
174
+ | Name | Signature | Description |
175
+ |:-----|:----------|:------------|
176
+ | `parseSortString` | `(sortString: string) => [string, SortOrder][]` | Parses a sort string into Mongoose sort array format. Example: `"name -createdAt"` → `[["name", 1], ["createdAt", -1]]` |
177
+ | `parseAggregateSortString` | `(sortString: string) => {[key: string]: SortOrder}` | Parses a sort string into aggregation pipeline sort object. Example: `"name -createdAt"` → `{ name: 1, createdAt: -1 }` |
178
+
179
+ ```typescript
180
+ import { parseSortString, parseAggregateSortString } from '@r5v/mongoose-paginate'
181
+
182
+ const sortArray = parseSortString('name 1, createdAt -1')
183
+ // Result: [["name", 1], ["createdAt", -1]]
184
+
185
+ const sortObj = parseAggregateSortString('name 1, createdAt -1')
186
+ // Result: { name: 1, createdAt: -1 }
187
+ ```
188
+
189
+ ### Dot Notation Utilities
190
+
191
+ | Name | Signature | Description |
192
+ |:-----|:----------|:------------|
193
+ | `getPropertyFromDotNotation` | `(obj: any, path: string) => any` | Gets a nested property value using dot notation path |
194
+ | `dotNotationToObject` | `(dotString: string, value?: unknown) => object` | Converts a dot notation string to a nested object |
195
+ | `createObjectFromDotNotation` | `(dotNotationMap: {[key: string]: any}) => object` | Creates a nested object from multiple dot notation key-value pairs |
196
+ | `setPropertyFromDotNotation` | `(obj: Record<string, unknown>, path: string, value: unknown) => object` | Sets a nested property value (mutates original object) |
197
+ | `setPropertiesFromDotNotation` | `(obj: Record<string, unknown>, dotNotationMap: Record<string, unknown>) => object` | Sets multiple nested properties (mutates original object) |
198
+ | `setPropertyFromDotNotationImmutable` | `(obj: Record<string, unknown>, path: string, value: unknown) => object` | Sets a nested property value (returns new object) |
199
+ | `setPropertiesFromDotNotationImmutable` | `(obj: Record<string, unknown>, dotNotationMap: Record<string, unknown>) => object` | Sets multiple nested properties (returns new object) |
200
+
201
+ ```typescript
202
+ import {
203
+ getPropertyFromDotNotation,
204
+ dotNotationToObject,
205
+ setPropertyFromDotNotation
206
+ } from '@r5v/mongoose-paginate'
207
+
208
+ // Get nested value
209
+ const user = { profile: { name: 'John', address: { city: 'NYC' } } }
210
+ getPropertyFromDotNotation(user, 'profile.address.city') // 'NYC'
211
+
212
+ // Create nested object from dot notation
213
+ dotNotationToObject('user.profile.name', 'John')
214
+ // Result: { user: { profile: { name: 'John' } } }
215
+
216
+ // Set nested property
217
+ const obj = { user: { name: 'John' } }
218
+ setPropertyFromDotNotation(obj, 'user.email', 'john@example.com')
219
+ // Result: { user: { name: 'John', email: 'john@example.com' } }
220
+ ```
221
+
222
+ ### Validation Utilities
223
+
224
+ | Name | Signature | Description |
225
+ |:-----|:----------|:------------|
226
+ | `isJsonString` | `(str: string) => boolean` | Checks if a string is valid JSON |
227
+ | `isValidDateString` | `(value: string) => boolean` | Checks if a string is a valid ISO 8601 date format |
228
+
229
+ ```typescript
230
+ import { isJsonString, isValidDateString } from '@r5v/mongoose-paginate'
231
+
232
+ isJsonString('{"name": "John"}') // true
233
+ isJsonString('invalid') // false
234
+
235
+ isValidDateString('2024-01-15') // true
236
+ isValidDateString('2024-01-15T10:30:00.000Z') // true
237
+ isValidDateString('invalid-date') // false
238
+ ```
239
+
240
+ ### Schema Traversal Utilities
241
+
242
+ | Name | Signature | Description |
243
+ |:-----|:----------|:------------|
244
+ | `buildFullPath` | `(parentPath: string, childPath: string) => string` | Builds a dot-notation path from parent and child segments |
245
+ | `traverseSchemaObject` | `(obj: any, callback: (obj, path) => void, currentPath?: string) => void` | Recursively traverses a Mongoose schema object, calling callback for each node |
246
+
247
+ ```typescript
248
+ import { buildFullPath, traverseSchemaObject } from '@r5v/mongoose-paginate'
249
+
250
+ // Build dot-notation paths
251
+ buildFullPath('user', 'profile') // 'user.profile'
252
+ buildFullPath('', 'name') // 'name'
253
+ buildFullPath('parent', '') // 'parent'
254
+
255
+ // Traverse schema objects
256
+ traverseSchemaObject(schemaType, (obj, currentPath) => {
257
+ if (obj.options?.ref) {
258
+ console.log(`Found ref at ${currentPath}: ${obj.options.ref}`)
259
+ }
260
+ })
261
+ ```
262
+
263
+ ## Types
264
+
265
+ All TypeScript types are exported and can be imported:
266
+
267
+ ```typescript
268
+ import type {
269
+ PagingQueryOptions,
270
+ AggregateQueryOptions,
271
+ QueryParameters,
272
+ PagingQueryParsedRequestParams,
273
+ AggregateQueryParsedRequestParams
274
+ } from '@r5v/mongoose-paginate'
275
+
276
+ // Or from the types subpath
277
+ import type * from '@r5v/mongoose-paginate/types'
278
+ ```
279
+
280
+ ## Build
281
+
282
+ ```text
283
+ ### build and run test server
284
+
285
+ $ yarn
286
+ $ yarn run build
287
+ $ cd test_server
288
+ $ yarn
289
+ $ yarn add ../ #adds the package to the local server
290
+ $ echo MONGODB_URI=http://localhost:27017/bookstore >> .env
291
+ $ yarn run seed
292
+ ### load seed data into bookstore database
293
+ $ yarn run start
294
+ ```
295
+
296
+
297
+ #### Aggregations Order of operations
298
+
299
+ 1. First pipeline stage (if `$search`, `$searchMeta`, or `$geoNear`)
300
+ 2. `$match` combining: `staticFilter` + `$filter` (if `enableFilter`) + first pipeline `$match` stage
301
+ 3. `$preSort` (if `enablePreSort` is true)
302
+ 4. Remaining pipeline stages
303
+ 5. `$select` / `$project`
304
+ 6. `$count` (adds `_count` fields for array sizes)
305
+ 7. `$postFilter` combining: `staticPostFilter` + `$postFilter` (if `enablePostFilter`)
306
+ 8. `$sort` (final sorting, can sort on computed fields)
307
+ 9. Apply pagination (`$skip`, `$limit`) and options
308
+
309
+
310
+ ### 1.0.15
311
+ - **Re-enabled `removeProtected` option** for `AggregationPagingQuery` (EXPERIMENTAL) - Automatically excludes fields marked with `select: false` in your schema (e.g., passwords, secret keys) from aggregation results. Use with caution and test thoroughly in your environment.
312
+ - Uses refactored `findProtectedPaths` utility which safely traverses schemas without JSON serialization
313
+
314
+ ### 1.0.14
315
+ - Added proper TypeScript package exports with subpaths (`/utils`, `/types`)
316
+ - Exported all utility functions (dot notation, sort parsing, validation)
317
+ - Exported all TypeScript types
318
+ - **Fixed Express Request type compatibility** - Added `RequestLike` interface to allow custom request types without index signature issues
319
+ - Fixed JSON.parse crash on malformed `$filter`/`$postFilter` parameters
320
+ - Fixed regex global flag bug in populate parsing
321
+ - Added input validation to constructors
322
+ - Improved type safety (reduced `any` usage)
323
+ - Removed deprecated `$includes` parameter
324
+ - Replaced `JSON.parse(JSON.stringify())` with `structuredClone()`
325
+ - Fixed inconsistent equality operator (`==` to `===`)
326
+ - **Fixed empty pipeline crash** - `AggregationPagingQuery.initQuery` no longer crashes when pipeline is empty
327
+ - **Refactored `buildPopulate`** - Extracted inner functions to module level for better testability
328
+ - **Refactored `findProtectedPaths`** - Removed JSON.stringify that could fail on circular references
329
+ - **Refactored `getPathsWithRef`** - Simplified input handling, removed brittle string parsing
330
+ - **Added `schemaTraversal` utility** - Shared `buildFullPath` and `traverseSchemaObject` functions for schema traversal
331
+
332
+ ### 1.0.13
333
+ - Fix issue where disablePaging was not working on aggregation query
334
+
335
+ ### 1.0.12
336
+ - Fix issue with AggregationPagingQuery where static post filter would not be applied if $postFilter param was not supplied
337
+ - updated typings on AggregationPagingQuery to include enablePostFilter, enableFilter, and enablePreSort
338
+ - flipped PagingQuery back to `disableFilter` instead of `enableFilter` option \# this was set incorrectly in 1.0.11 but still defaults to false
339
+
340
+ ### 1.0.11
341
+ Fix Issue with Typescript build
342
+
343
+ ### 1.0.9
344
+ Fix Issue with Typescript add buildPopulate Export
345
+
346
+ ### 1.0.8
347
+ Adds Deep Populate and Select Notation
348
+
@@ -1 +1 @@
1
- {"version":3,"file":"aggregationPagingQuery.d.ts","sourceRoot":"","sources":["../src/aggregationPagingQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,EACL,SAAS,EAKZ,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAC,qBAAqB,EAAE,iCAAiC,EAAE,WAAW,EAAC,MAAM,SAAS,CAAA;AAQlG,qBAAa,sBAAsB;IAC/B,MAAM,EAAG,iCAAiC,CAYzC;IACD,OAAO,EAAE,qBAAqB,CAK7B;IACD,KAAK,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC,GAAG,SAAS,CAAA;IACvC,cAAc,EAAE,MAAM,EAAE,CAAK;IAC7B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;gBACL,GAAG,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,qBAAqB;IAiB/E,kBAAkB,kCAAqB;IACvC,WAAW,sPAAc;IACzB,iBAAiB,6BAAoB;IACrC,YAAY,2BAAe;IAC3B,eAAe,mEAAkB;IACjC,wBAAwB;;MAA2B;IACnD,YAAY,aAOX;IACD,SAAS,sBAkDR;IACD,cAAc,GAAI,CAAC,EAAE,UAAU,CAAC,KAAG,CAAC,CAmCnC;IAED,OAAO,CAAC,qBAAqB,CAS5B;IACD,IAAI,yBAgCH;CAEJ"}
1
+ {"version":3,"file":"aggregationPagingQuery.d.ts","sourceRoot":"","sources":["../src/aggregationPagingQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,EACL,SAAS,EAKZ,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAC,qBAAqB,EAAE,iCAAiC,EAAE,WAAW,EAAC,MAAM,SAAS,CAAA;AAQlG,qBAAa,sBAAsB;IAC/B,MAAM,EAAG,iCAAiC,CAYzC;IACD,OAAO,EAAE,qBAAqB,CAM7B;IACD,KAAK,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC,GAAG,SAAS,CAAA;IACvC,cAAc,EAAE,MAAM,EAAE,CAAK;IAC7B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;gBACL,GAAG,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,qBAAqB;IAoB/E,kBAAkB,kCAAqB;IACvC,WAAW,sPAAc;IACzB,iBAAiB,6BAAoB;IACrC,YAAY,2BAAe;IAC3B,eAAe,mEAAkB;IACjC,wBAAwB;;MAA2B;IACnD,YAAY,aAOX;IACD,SAAS,sBAsDR;IACD,cAAc,GAAI,CAAC,EAAE,UAAU,CAAC,KAAG,CAAC,CAmCnC;IAED,OAAO,CAAC,qBAAqB,CAS5B;IACD,IAAI,yBAgCH;CAEJ"}
@@ -45,6 +45,7 @@ class AggregationPagingQuery {
45
45
  enableFilter: false,
46
46
  enablePostFilter: false,
47
47
  enablePreSort: true,
48
+ removeProtected: false,
48
49
  pipeline: []
49
50
  };
50
51
  this.protectedPaths = [];
@@ -65,7 +66,7 @@ class AggregationPagingQuery {
65
66
  };
66
67
  this.initQuery = () => __awaiter(this, void 0, void 0, function* () {
67
68
  const { $filter, $sort, $preSort, $select, $count, $postFilter } = this.params;
68
- const _a = this.options, { enableFilter, enablePreSort, enablePostFilter, staticFilter, staticPostFilter, pipeline } = _a, options = __rest(_a, ["enableFilter", "enablePreSort", "enablePostFilter", "staticFilter", "staticPostFilter", "pipeline"]);
69
+ const _a = this.options, { enableFilter, enablePreSort, enablePostFilter, staticFilter, staticPostFilter, removeProtected, pipeline } = _a, options = __rest(_a, ["enableFilter", "enablePreSort", "enablePostFilter", "staticFilter", "staticPostFilter", "removeProtected", "pipeline"]);
69
70
  this.query = this.model.aggregate();
70
71
  const [p1, ...pipes] = pipeline;
71
72
  const filterObj = { $and: [Object.assign({}, staticFilter)] };
@@ -100,6 +101,9 @@ class AggregationPagingQuery {
100
101
  if ($select) {
101
102
  this.query.project($select);
102
103
  }
104
+ if (removeProtected) {
105
+ this.removeProtectedFields();
106
+ }
103
107
  if ($count.length) {
104
108
  this.createCounts();
105
109
  }
@@ -191,6 +195,9 @@ class AggregationPagingQuery {
191
195
  this.options = Object.assign(Object.assign({}, this.options), options);
192
196
  this.model = model;
193
197
  this.params = this.parseParams(this.params, req.query, true);
198
+ if (this.options.removeProtected) {
199
+ this.protectedPaths = this.findProtectedPaths(model);
200
+ }
194
201
  this.initQuery();
195
202
  }
196
203
  }
@@ -0,0 +1,81 @@
1
+ {
2
+ "name": "@r5v/mongoose-paginate",
3
+ "version": "1.0.16",
4
+ "main": "./dist/index.js",
5
+ "module": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "require": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./utils": {
15
+ "types": "./dist/utils/index.d.ts",
16
+ "import": "./dist/utils/index.js",
17
+ "require": "./dist/utils/index.js",
18
+ "default": "./dist/utils/index.js"
19
+ },
20
+ "./types": {
21
+ "types": "./dist/types/index.d.ts",
22
+ "import": "./dist/types/index.js",
23
+ "require": "./dist/types/index.js",
24
+ "default": "./dist/types/index.js"
25
+ }
26
+ },
27
+ "scripts": {
28
+ "prebuild": "rimraf dist/",
29
+ "build": "tsc",
30
+ "postbuild": "copyfiles --error package.json README.md dist/",
31
+ "test": "concurrently --kill-others-on-fail --prefix none npm:test:*",
32
+ "test:unit": "jest"
33
+ },
34
+ "keywords": [
35
+ "mongoose",
36
+ "paging",
37
+ "mongodb"
38
+ ],
39
+ "license": "ISC",
40
+ "homepage": "https://github.com/RedFiveVentures/mongoose-paginate",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/RedFiveVentures/mongoose-paginate"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/RedFiveVentures/mongoose-paginate/issues"
47
+ },
48
+ "author": {
49
+ "name": "Noah Wallace",
50
+ "email": "noah@redfiveventures.com",
51
+ "url": "https://www.npmjs.com/~nwrfv"
52
+ },
53
+ "files": [
54
+ "package.json",
55
+ "./dist",
56
+ "README.md"
57
+ ],
58
+ "engines": {
59
+ "node": ">=20"
60
+ },
61
+ "dependencies": {
62
+ "mongoose": "^8.16.1",
63
+ "qs": "^6.14.0"
64
+ },
65
+ "description": "A lightweight Node.js package that seamlessly bridges RESTful API query parameters to Mongoose operations. Automatically parses and transforms URL query strings into valid Mongoose queries, supporting filtering, sorting, pagination, field selection, and population. Simply pass your Express req.query object and get back a fully configured Mongoose query ready for execution. Perfect for rapidly building consistent, feature-rich APIs without repetitive query parsing logic",
66
+ "devDependencies": {
67
+ "@types/express": "^5.0.3",
68
+ "@types/jest": "^30.0.0",
69
+ "@types/node": "^24.0.10",
70
+ "concurrently": "^9.2.0",
71
+ "copyfiles": "^2.4.1",
72
+ "jest": "^30.0.4",
73
+ "mockingoose": "^2.16.2",
74
+ "node-mocks-http": "^1.17.2",
75
+ "rimraf": "^6.0.1",
76
+ "ts-jest": "^29.4.0",
77
+ "ts-node-dev": "^2.0.0",
78
+ "tsx": "^4.20.3",
79
+ "typescript": "^5.8.3"
80
+ }
81
+ }
@@ -56,6 +56,18 @@ const AggTestSchema = new mongoose_1.Schema({
56
56
  category: { type: mongoose_1.Schema.Types.ObjectId, ref: 'Category' }
57
57
  });
58
58
  const AggTestModel = mongoose_1.default.model('AggTestModel', AggTestSchema);
59
+ // Create a test schema with protected fields
60
+ const ProtectedSchema = new mongoose_1.Schema({
61
+ username: { type: String, required: true },
62
+ email: { type: String },
63
+ password: { type: String, select: false },
64
+ secretKey: { type: String, select: false },
65
+ profile: {
66
+ name: { type: String },
67
+ ssn: { type: String, select: false }
68
+ }
69
+ });
70
+ const ProtectedModel = mongoose_1.default.model('ProtectedModel', ProtectedSchema);
59
71
  // Default pipeline with at least one stage to avoid undefined error
60
72
  const defaultPipeline = [{ $match: {} }];
61
73
  describe('AggregationPagingQuery', () => {
@@ -362,4 +374,46 @@ describe('AggregationPagingQuery', () => {
362
374
  }).toThrow('Invalid JSON in $postFilter parameter');
363
375
  });
364
376
  });
377
+ describe('removeProtected', () => {
378
+ test('should find protected paths when removeProtected is enabled', () => {
379
+ const req = (0, node_mocks_http_1.createRequest)({ query: {} });
380
+ const apq = new aggregationPagingQuery_1.AggregationPagingQuery(req, ProtectedModel, {
381
+ pipeline: defaultPipeline,
382
+ removeProtected: true
383
+ });
384
+ expect(apq.protectedPaths).toContain('password');
385
+ expect(apq.protectedPaths).toContain('secretKey');
386
+ });
387
+ test('should not find protected paths when removeProtected is disabled', () => {
388
+ const req = (0, node_mocks_http_1.createRequest)({ query: {} });
389
+ const apq = new aggregationPagingQuery_1.AggregationPagingQuery(req, ProtectedModel, {
390
+ pipeline: defaultPipeline,
391
+ removeProtected: false
392
+ });
393
+ expect(apq.protectedPaths).toEqual([]);
394
+ });
395
+ test('should not find protected paths by default', () => {
396
+ const req = (0, node_mocks_http_1.createRequest)({ query: {} });
397
+ const apq = new aggregationPagingQuery_1.AggregationPagingQuery(req, ProtectedModel, {
398
+ pipeline: defaultPipeline
399
+ });
400
+ expect(apq.protectedPaths).toEqual([]);
401
+ });
402
+ test('should set removeProtected option correctly', () => {
403
+ const req = (0, node_mocks_http_1.createRequest)({ query: {} });
404
+ const apq = new aggregationPagingQuery_1.AggregationPagingQuery(req, ProtectedModel, {
405
+ pipeline: defaultPipeline,
406
+ removeProtected: true
407
+ });
408
+ expect(apq.options.removeProtected).toBe(true);
409
+ });
410
+ test('should have empty protected paths for model without protected fields', () => {
411
+ const req = (0, node_mocks_http_1.createRequest)({ query: {} });
412
+ const apq = new aggregationPagingQuery_1.AggregationPagingQuery(req, AggTestModel, {
413
+ pipeline: defaultPipeline,
414
+ removeProtected: true
415
+ });
416
+ expect(apq.protectedPaths).toEqual([]);
417
+ });
418
+ });
365
419
  });
@@ -59,9 +59,15 @@ export interface AggregateQueryOptions extends Omit<AggregateOptions, 'comment'>
59
59
  disablePaging?: boolean;
60
60
  disablePostFilter?: boolean;
61
61
  disablePreSort?: boolean;
62
+ enablePostFilter?: boolean;
63
+ enablePreSort?: boolean;
64
+ staticFilter?: {
65
+ [key: string]: any;
66
+ };
62
67
  staticPostFilter?: {
63
68
  [key: string]: any;
64
69
  };
70
+ removeProtected?: boolean;
65
71
  pipeline: mongoose.PipelineStage[];
66
72
  }
67
73
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,EAAE,EAAC,YAAY,EAAE,SAAS,EAAE,gBAAgB,EAAC,MAAM,UAAU,CAAC;AAC7E,OAAO,EAAC,QAAQ,EAAC,MAAM,IAAI,CAAC;AAE5B;;;;GAIG;AACH,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC7C;AAED,MAAM,WAAW,eAAgB,SAAQ,QAAQ;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,KAAK,GAAG,IAAI,GAAG,GAAG,GAAG,OAAO,CAAA;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,2BAA2B;IACxC,OAAO,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAA;IAChC,MAAM,EAAE,MAAM,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A;KAAE,CAAA;IACtC,KAAK,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,CAAA;IACnC,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,WAAW,EAAE;QAAC,CAAC,GAAG,EAAC,MAAM,GAAE,GAAG,CAAA;KAAC,CAAA;CAClC;AACD,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACtD,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,aAAa,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,MAAM,WAAW,kBAAmB,SAAQ,oBAAoB;IAC5D,YAAY,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAA;IACrC,MAAM,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,qBAAsB,SAAQ,IAAI,CAAC,gBAAgB,EAAC,SAAS,CAAC;IAC3E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAA;IACrC,gBAAgB,CAAC,EAAE;QAAE,CAAC,GAAG,EAAC,MAAM,GAAG,GAAG,CAAA;KAAE,CAAA;IACxC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,QAAQ,CAAC,aAAa,EAAE,CAAA;CACrC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r5v/mongoose-paginate",
3
- "version": "1.0.14",
3
+ "version": "1.0.16",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,7 +27,7 @@
27
27
  "scripts": {
28
28
  "prebuild": "rimraf dist/",
29
29
  "build": "tsc",
30
- "copy-files": "copyfiles --error package.json dist/",
30
+ "postbuild": "copyfiles --error package.json README.md dist/",
31
31
  "test": "concurrently --kill-others-on-fail --prefix none npm:test:*",
32
32
  "test:unit": "jest"
33
33
  },