mongoose-query-find 1.1.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 ADDED
@@ -0,0 +1,231 @@
1
+ # mongoose-query-find
2
+
3
+ > A TypeScript utility for Mongoose that simplifies building dynamic, chainable queries with filtering, global search, sorting, field selection, and pagination.
4
+
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
39
+
40
+ ---
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ npm install mongoose-query-find
46
+ ```
47
+
48
+ > **Peer dependency:** Requires `mongoose@^8` or `mongoose@^9`.
49
+
50
+ ---
51
+
52
+ ## Quick Start
53
+
54
+ ```typescript
55
+ import QueryFind from 'mongoose-query-find';
56
+ import { Request, Response } from 'express';
57
+ import Product from './models/Product';
58
+
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();
65
+
66
+ const products = await features.exec();
67
+
68
+ res.json({ results: products.length, data: products });
69
+ };
70
+ ```
71
+
72
+ ---
73
+
74
+ ## API Reference
75
+
76
+ ### `new QueryFind(query, queryString)`
77
+
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 |
82
+
83
+ ---
84
+
85
+ ### `filter()`
86
+
87
+ Applies field-level filtering from the query string. Automatically prepends `$` to MongoDB operators and wraps plain string values in a case-insensitive regex.
88
+
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`
90
+
91
+ **Example URL:**
92
+
93
+ ```
94
+ GET /api/products?price[gte]=100&category=electronics
95
+ ```
96
+
97
+ ---
98
+
99
+ ### `globalFilter(fields)`
100
+
101
+ Performs a global search across the specified fields using the `q` query parameter with case-insensitive regex.
102
+
103
+ | Parameter | Type | Description |
104
+ | --------- | ---------- | ------------------------------------- |
105
+ | `fields` | `string[]` | Array of field names to search across |
106
+
107
+ **Example:**
108
+
109
+ ```typescript
110
+ new QueryFind(Product.find(), req.query)
111
+ .globalFilter(['name', 'description', 'brand'])
112
+ .paginate();
113
+ ```
114
+
115
+ **Example URL:**
116
+
117
+ ```
118
+ GET /api/products?q=wireless+headphones
119
+ ```
120
+
121
+ ---
122
+
123
+ ### `sort()`
124
+
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:**
128
+
129
+ ```
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
133
+ ```
134
+
135
+ ---
136
+
137
+ ### `limitFields()`
138
+
139
+ Selects specific fields to include or exclude using the `fields` query parameter. Defaults to excluding `__v`.
140
+
141
+ **Example URLs:**
142
+
143
+ ```
144
+ GET /api/products?fields=name,price,category # include only these fields
145
+ GET /api/products?fields=-description,-__v # exclude these fields
146
+ ```
147
+
148
+ ---
149
+
150
+ ### `paginate()`
151
+
152
+ Applies skip/limit pagination using `page` and `limit` query parameters.
153
+
154
+ | Parameter | Default | Description |
155
+ | --------- | ------- | -------------------------- |
156
+ | `page` | `1` | Page number (1-indexed) |
157
+ | `limit` | `100` | Number of results per page |
158
+
159
+ **Example URL:**
160
+
161
+ ```
162
+ GET /api/products?page=2&limit=20
163
+ ```
164
+
165
+ ---
166
+
167
+ ### `exec()`
168
+
169
+ Executes the built query and returns a `Promise<T[]>`.
170
+
171
+ ```typescript
172
+ const results = await features.exec();
173
+ ```
174
+
175
+ ---
176
+
177
+ ## Query String Parameters
178
+
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` |
188
+
189
+ ---
190
+
191
+ ## Examples
192
+
193
+ ### Combined Usage
194
+
195
+ ```typescript
196
+ // GET /api/products?q=phone&price[gte]=200&sort=-createdAt&fields=name,price&page=1&limit=10
197
+
198
+ const features = new QueryFind(Product.find(), req.query)
199
+ .globalFilter(['name', 'description'])
200
+ .filter()
201
+ .sort()
202
+ .limitFields()
203
+ .paginate();
204
+
205
+ const products = await features.exec();
206
+ ```
207
+
208
+ ### Filtering with Operators
209
+
210
+ ```
211
+ GET /api/products?price[gte]=100&price[lte]=500&stock[gt]=0
212
+ ```
213
+
214
+ ```typescript
215
+ // Equivalent to:
216
+ Product.find({ price: { $gte: 100, $lte: 500 }, stock: { $gt: 0 } });
217
+ ```
218
+
219
+ ### Pagination
220
+
221
+ ```
222
+ GET /api/products?page=2&limit=15
223
+ ```
224
+
225
+ Skips the first 15 results and returns the next 15.
226
+
227
+ ---
228
+
229
+ ## License
230
+
231
+ [ISC](https://opensource.org/licenses/ISC) © [jsdev.robin@gmail.com](mailto:jsdev.robin@gmail.com)
@@ -0,0 +1,21 @@
1
+ import { Document, Query } from 'mongoose';
2
+ interface QueryParams {
3
+ page?: string;
4
+ limit?: string;
5
+ sort?: string;
6
+ fields?: string;
7
+ [key: string]: string | number | unknown;
8
+ }
9
+ declare class QueryFind<T extends Document> {
10
+ query: Query<T[], T>;
11
+ queryString: QueryParams;
12
+ constructor(query: Query<T[], T>, queryString: QueryParams);
13
+ filter(): this;
14
+ globalFilter(fields: string[]): this;
15
+ sort(): this;
16
+ limitFields(): this;
17
+ paginate(): this;
18
+ exec(): Promise<T[]>;
19
+ }
20
+ export default QueryFind;
21
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +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;IAwBd,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI;IAapC,IAAI,IAAI,IAAI;IAWZ,WAAW,IAAI,IAAI;IAWnB,QAAQ,IAAI,IAAI;IAUV,IAAI,IAAI,OAAO,CAAC,CAAC,EAAE,CAAC;CAG3B;AAED,eAAe,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class QueryFind {
4
+ constructor(query, queryString) {
5
+ this.query = query;
6
+ this.queryString = queryString;
7
+ }
8
+ 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 (typeof val === 'string') {
18
+ parsedQuery[key] = { $regex: val, $options: 'i' };
19
+ }
20
+ });
21
+ this.query = this.query.find(parsedQuery);
22
+ return this;
23
+ }
24
+ globalFilter(fields) {
25
+ const search = this.queryString.q;
26
+ if (search && fields.length > 0) {
27
+ const orConditions = fields.map((field) => ({
28
+ [field]: { $regex: search, $options: 'i' },
29
+ }));
30
+ this.query = this.query.model.find();
31
+ this.query = this.query.find({ $or: orConditions });
32
+ }
33
+ return this;
34
+ }
35
+ sort() {
36
+ if (this.queryString.sort) {
37
+ const sortBy = this.queryString.sort.split(',').join(' ');
38
+ this.query = this.query.sort(sortBy);
39
+ }
40
+ else {
41
+ this.query = this.query.sort('-createdAt');
42
+ }
43
+ return this;
44
+ }
45
+ limitFields() {
46
+ if (this.queryString.fields) {
47
+ const fields = this.queryString.fields.split(',').join(' ');
48
+ this.query = this.query.select(fields);
49
+ }
50
+ else {
51
+ this.query = this.query.select('-__v');
52
+ }
53
+ return this;
54
+ }
55
+ paginate() {
56
+ const page = parseInt(this.queryString.page || '1', 10);
57
+ const limit = parseInt(this.queryString.limit || '100', 10);
58
+ const skip = (page - 1) * limit;
59
+ this.query = this.query.skip(skip).limit(limit);
60
+ return this;
61
+ }
62
+ async exec() {
63
+ return await this.query.exec();
64
+ }
65
+ }
66
+ exports.default = QueryFind;
67
+ // Ref
68
+ // new QueryFind(collection.find(), query)
69
+ // .filter()
70
+ // .sort()
71
+ // .limitFields()
72
+ // .paginate();
73
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,O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AC,CAAC,GAAG,KAAK,CAAC;QAEhC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAEhD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,IAAI;QACR,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;IACjC,CAAC;CACF;AAED,kBAAe,SAAS,CAAC;AAEzB,MAAM;AACN,0CAA0C;AAC1C,cAAc;AACd,YAAY;AACZ,mBAAmB;AACnB,iBAAiB"}
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "mongoose-query-find",
3
+ "version": "1.1.0",
4
+ "private": false,
5
+ "files": [
6
+ "dist"
7
+ ],
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "main": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.js",
17
+ "types": "./dist/index.d.ts"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "prepublishOnly": "npm run build"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/jsdev-robin/mongoose-query-find.git"
27
+ },
28
+ "author": "jsdev.robin@gmail.com",
29
+ "license": "ISC",
30
+ "bugs": {
31
+ "url": "https://github.com/jsdev-robin/mongoose-query-find/issues"
32
+ },
33
+ "keywords": [
34
+ "mongoose",
35
+ "typescript",
36
+ "query-builder",
37
+ "pagination",
38
+ "filtering",
39
+ "sorting",
40
+ "field-limiting",
41
+ "regex-search",
42
+ "global-search",
43
+ "api-query",
44
+ "mongodb",
45
+ "document-query",
46
+ "dynamic-query",
47
+ "query-helper",
48
+ "async-query",
49
+ "crud-utilities"
50
+ ],
51
+ "homepage": "https://github.com/jsdev-robin/mongoose-query-find#readme",
52
+ "description": "QueryFind is a TypeScript utility for Mongoose that simplifies building dynamic queries. It supports advanced filtering, global search across multiple fields, sorting, field selection, and pagination for MongoDB documents, making API query handling more efficient and maintainable.",
53
+ "peerDependencies": {
54
+ "mongoose": "^8 || ^9"
55
+ },
56
+ "devDependencies": {
57
+ "@eslint/js": "^10.0.1",
58
+ "@types/node": "^25.5.0",
59
+ "eslint": "^10.1.0",
60
+ "globals": "^17.4.0",
61
+ "jiti": "^2.6.1",
62
+ "typescript": "5.2.2",
63
+ "typescript-eslint": "^8.58.0"
64
+ }
65
+ }