{"id":13659284,"url":"https://github.com/loris/api-query-params","last_synced_at":"2026-01-06T11:20:11.308Z","repository":{"id":41440579,"uuid":"49519385","full_name":"loris/api-query-params","owner":"loris","description":"Convert URL query parameters to MongoDB queries","archived":false,"fork":false,"pushed_at":"2023-03-04T03:23:22.000Z","size":963,"stargazers_count":176,"open_issues_count":14,"forks_count":34,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-17T08:29:09.832Z","etag":null,"topics":["api","mongodb","mongodb-query","mongoose","query-builder","url"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/loris.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2016-01-12T18:12:42.000Z","updated_at":"2025-02-11T15:48:26.000Z","dependencies_parsed_at":"2024-01-15T20:48:25.492Z","dependency_job_id":"e6227177-5a89-46ee-9aa6-cf45b3138e8a","html_url":"https://github.com/loris/api-query-params","commit_stats":{"total_commits":167,"total_committers":11,"mean_commits":"15.181818181818182","dds":"0.11377245508982037","last_synced_commit":"a83e88df2f38b560f74adf1443594298a0c46698"},"previous_names":[],"tags_count":51,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loris%2Fapi-query-params","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loris%2Fapi-query-params/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loris%2Fapi-query-params/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loris%2Fapi-query-params/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/loris","download_url":"https://codeload.github.com/loris/api-query-params/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250360249,"owners_count":21417717,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","mongodb","mongodb-query","mongoose","query-builder","url"],"created_at":"2024-08-02T05:01:07.040Z","updated_at":"2026-01-06T11:20:11.256Z","avatar_url":"https://github.com/loris.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# api-query-params\n\n[![NPM version][npm-image]][npm-url]\n[![Build Status][travis-image]][travis-url]\n[![Coveralls Status][coveralls-image]][coveralls-url]\n[![Dependency Status][depstat-image]][depstat-url]\n[![Downloads][download-badge]][npm-url]\n\n\u003e Convert query parameters from API urls to MongoDB queries (advanced querying, filtering, sorting, …)\n\n## Features\n\n- **Powerful**. Supports most of MongoDB operators (`$in`, `$regexp`, …) and features (nested objects, projection, type casting, …)\n- **Custom**. Allows customization of keys (ie, `fields` vs `select`) and options\n- **Agnostic.** Works with any web frameworks (Express, Koa, …) and/or MongoDB libraries (mongoose, mongoskin, …)\n- **Simple.** ~200 LOCs, dependency-free ES6 code\n- **Fully tested.** 100% code coverage\n\n## Install\n\n```sh\nnpm i --save api-query-params\n```\n\n## Usage\n\n#### API\n\n`aqp(queryString, [opts])`\n\n\u003e Converts `queryString` into a MongoDB query object\n\n###### Arguments\n\n- `queryString`: query string part of the requested API URL (ie, `firstName=John\u0026limit=10`). Works with already parsed object too (ie, `{status: 'success'}`) [required]\n- `opts`: object for advanced options (See below) [optional]\n\n###### Returns\n\nThe resulting object contains the following properties:\n\n- `filter` which contains the query criteria\n- `projection` which contains the query projection\n- `sort`, `skip`, `limit` which contains the cursor modifiers\n- `population` which contains the query population ([mongoose feature only](https://mongoosejs.com/docs/populate.html))\n\n#### Example\n\n```js\nimport aqp from 'api-query-params';\n\nconst query = aqp(\n  'status=sent\u0026timestamp\u003e2016-01-01\u0026author.firstName=/john/i\u0026limit=100\u0026skip=50\u0026sort=-timestamp\u0026populate=logs\u0026fields=id,logs.ip'\n);\n//  {\n//    filter: {\n//      status: 'sent',\n//      timestamp: { $gt: Fri Jan 01 2016 01:00:00 GMT+0100 (CET) },\n//      'author.firstName': /john/i\n//    },\n//    sort: { timestamp: -1 },\n//    skip: 50,\n//    limit: 100,\n//    projection: { id: 1 },\n//    population: [ { path: 'logs', select: { ip: 1 } } ]\n//  }\n```\n\n#### Example with Express and mongoose\n\n```js\nimport express from 'express';\nimport aqp from 'api-query-params';\nimport User from './models/User';\n\nconst app = express();\n\napp.get('/users', (req, res, next) =\u003e {\n  const { filter, skip, limit, sort, projection, population } = aqp(req.query);\n  User.find(filter)\n    .skip(skip)\n    .limit(limit)\n    .sort(sort)\n    .select(projection)\n    .populate(population)\n    .exec((err, users) =\u003e {\n      if (err) {\n        return next(err);\n      }\n\n      res.send(users);\n    });\n});\n```\n\nThat's it. Your `/users` endpoint can now query, filter, sort your `User` mongoose model and more.\n\n## Supported features\n\n#### Filtering operators\n\n| MongoDB   | URI                  | Example                 | Result                                                                  |\n| --------- | -------------------- | ----------------------- | ----------------------------------------------------------------------- |\n| `$eq`     | `key=val`            | `type=public`           | `{filter: {type: 'public'}}`                                            |\n| `$gt`     | `key\u003eval`            | `count\u003e5`               | `{filter: {count: {$gt: 5}}}`                                           |\n| `$gte`    | `key\u003e=val`           | `rating\u003e=9.5`           | `{filter: {rating: {$gte: 9.5}}}`                                       |\n| `$lt`     | `key\u003cval`            | `createdAt\u003c2016-01-01`  | `{filter: {createdAt: {$lt: Fri Jan 01 2016 01:00:00 GMT+0100 (CET)}}}` |\n| `$lte`    | `key\u003c=val`           | `score\u003c=-5`             | `{filter: {score: {$lte: -5}}}`                                         |\n| `$ne`     | `key!=val`           | `status!=success`       | `{filter: {status: {$ne: 'success'}}}`                                  |\n| `$in`     | `key=val1,val2`      | `country=GB,US`         | `{filter: {country: {$in: ['GB', 'US']}}}`                              |\n| `$nin`    | `key!=val1,val2`     | `lang!=fr,en`           | `{filter: {lang: {$nin: ['fr', 'en']}}}`                                |\n| `$exists` | `key`                | `phone`                 | `{filter: {phone: {$exists: true}}}`                                    |\n| `$exists` | `!key`               | `!email`                | `{filter: {email: {$exists: false}}}`                                   |\n| `$regex`  | `key=/value/\u003copts\u003e`  | `email=/@gmail\\.com$/i` | `{filter: {email: /@gmail.com$/i}}`                                     |\n| `$regex`  | `key!=/value/\u003copts\u003e` | `phone!=/^06/`          | `{filter: {phone: { $not: /^06/}}}`                                     |\n\nFor more advanced usage (`$or`, `$type`, `$elemMatch`, etc.), pass any MongoDB query filter object as JSON string in the `filter` query parameter, ie:\n\n```js\naqp('filter={\"$or\":[{\"key1\":\"value1\"},{\"key2\":\"value2\"}]}');\n//  {\n//    filter: {\n//      $or: [\n//        { key1: 'value1' },\n//        { key2: 'value2' }\n//      ]\n//    },\n//  }\n```\n\n#### Skip / Limit operators\n\n- Useful to limit the number of records returned.\n- Default operator keys are `skip` and `limit`.\n\n```js\naqp('skip=5\u0026limit=10');\n//  {\n//    skip: 5,\n//    limit: 10\n//  }\n```\n\n#### Projection operator\n\n- Useful to limit fields to return in each records.\n- Default operator key is `fields`.\n- It accepts a comma-separated list of fields. Default behavior is to specify fields to return. Use `-` prefixes to return all fields except some specific fields.\n- Due to a MongoDB limitation, you cannot combine inclusion and exclusion semantics in a single projection with the exception of the \\_id field.\n- It also accepts JSON string to use more powerful projection operators (`$`, `$elemMatch` or `$slice`)\n\n```js\naqp('fields=id,url');\n//  {\n//    projection: { id: 1, url: 1}\n//  }\n```\n\n```js\naqp('fields=-_id,-email');\n//  {\n//    projection: { _id: 0, email: 0 }\n//  }\n```\n\n```js\naqp('fields={\"comments\":{\"$slice\":[20,10]}}');\n//  {\n//    projection: { comments: { $slice: [ 20, 10 ] } }\n//  }\n```\n\n#### Sort operator\n\n- Useful to sort returned records.\n- Default operator key is `sort`.\n- It accepts a comma-separated list of fields. Default behavior is to sort in ascending order. Use `-` prefixes to sort in descending order.\n\n```js\naqp('sort=-points,createdAt');\n//  {\n//    sort: { points: -1, createdAt: 1 }\n//  }\n```\n\n#### Population operator\n\n- Useful to populate (reference documents in other collections) returned records. This is a [mongoose-only feature](https://mongoosejs.com/docs/populate.html).\n- Default operator key is `populate`.\n- It accepts a comma-separated list of fields.\n- It extracts projection on populated documents from the `projection` object.\n\n```js\naqp('populate=a,b\u0026fields=foo,bar,a.baz');\n// {\n//    population: [ { path: 'a', select: { baz: 1 } } ],\n//    projection: { foo: 1, bar: 1 },\n//  }\n```\n\n#### Keys with multiple values\n\nAny operators which process a list of fields (`$in`, `$nin`, sort and projection) can accept a comma-separated string or multiple pairs of key/value:\n\n- `country=GB,US` is equivalent to `country=GB\u0026country=US`\n- `sort=-createdAt,lastName` is equivalent to `sort=-createdAt\u0026sort=lastName`\n\n#### Embedded documents using `.` notation\n\nAny operators can be applied on deep properties using `.` notation:\n\n```js\naqp('followers[0].id=123\u0026sort=-metadata.created_at');\n//  {\n//    filter: {\n//      'followers[0].id': 123,\n//    },\n//    sort: { 'metadata.created_at': -1 }\n//  }\n```\n\n#### Automatic type casting\n\nThe following types are automatically casted: `Number`, `RegExp`, `Date` and `Boolean`. `null` string is also casted:\n\n```js\naqp('date=2016-01-01\u0026boolean=true\u0026integer=10\u0026regexp=/foobar/i\u0026null=null');\n// {\n//   filter: {\n//     date: Fri Jan 01 2016 01:00:00 GMT+0100 (CET),\n//     boolean: true,\n//     integer: 10,\n//     regexp: /foobar/i,\n//     null: null\n//   }\n// }\n```\n\nIf you need to disable or force type casting, you can wrap the values with `string()`, `date()` built-in casters or by specifying your own custom functions (See below):\n\n```js\naqp('key1=string(10)\u0026key2=date(2016)\u0026key3=string(null)');\n// {\n//   filter: {\n//     key1: '10',\n//     key2: Fri Jan 01 2016 01:00:00 GMT+0100 (CET),\n//     key3: 'null'\n//   }\n// }\n```\n\n## Available options (`opts`)\n\n#### Customize operator keys\n\nThe following options are useful to change the operator default keys:\n\n- `skipKey`: custom skip operator key (default is `skip`)\n- `limitKey`: custom limit operator key (default is `limit`)\n- `projectionKey`: custom projection operator key (default is `fields`)\n- `sortKey`: custom sort operator key (default is `sort`)\n- `filterKey`: custom filter operator key (default is `filter`)\n- `populationKey`: custom populate operator key (default is `populate`)\n\n```js\naqp('organizationId=123\u0026offset=10\u0026max=125', {\n  limitKey: 'max',\n  skipKey: 'offset',\n});\n// {\n//   filter: {\n//     organizationId: 123,\n//   },\n//   skip: 10,\n//   limit: 125\n// }\n```\n\n#### Blacklist / Whitelist\n\nThe following options are useful to specify which keys to use in the `filter` object. (ie, avoid that authentication parameter like `apiKey` ends up in a mongoDB query). All operator keys are (`sort`, `limit`, etc.) already ignored.\n\n- `blacklist`: filter on all keys except the ones specified\n- `whitelist`: filter only on the keys specified\n\n```js\naqp('id=e9117e5c-c405-489b-9c12-d9f398c7a112\u0026apiKey=foobar', {\n  blacklist: ['apiKey'],\n});\n// {\n//   filter: {\n//     id: 'e9117e5c-c405-489b-9c12-d9f398c7a112',\n//   }\n// }\n```\n\n#### Add custom casting functions\n\nYou can specify you own casting functions to apply to query parameter values, either by explicitly wrapping the value in URL with your custom function name (See example below) or by implictly mapping a key to a function (See `Specify casting per param keys` below). Note that you can also override built-in casting functions: `boolean`, `date` ,`null` ,`number` ,`regex` and `string`.\n\n- `casters`: object to specify custom casters, key is the caster name, and value is a function which is passed the query parameter value as parameter.\n\n```js\naqp('key1=lowercase(VALUE)\u0026key2=int(10.5)\u0026key3=true', {\n  casters: {\n    lowercase: val =\u003e val.toLowerCase(),\n    int: val =\u003e parseInt(val, 10),\n    boolean: val =\u003e (val === 'true' ? '1' : '0'),\n  },\n});\n// {\n//   filter: {\n//     key1: 'value',\n//     key2: 10,\n//     key3: '1',\n//   }\n// }\n```\n\n#### Specify casting per param keys\n\nYou can specify how query parameter values are casted by passing an object.\n\n- `castParams`: object which map keys to casters (built-in or custom ones using the `casters` option).\n\n```js\naqp('key1=VALUE\u0026key2=10.5\u0026key3=20\u0026key4=foo', {\n  casters: {\n    lowercase: val =\u003e val.toLowerCase(),\n    int: val =\u003e parseInt(val, 10),\n  },\n  castParams: {\n    key1: 'lowercase',\n    key2: 'int',\n    key3: 'string',\n    key4: 'unknown',\n  },\n});\n// {\n//   filter: {\n//     key1: 'value',\n//     key2: 10,\n//     key3: '20',\n//     key4: 'foo',\n//   }\n// }\n```\n\n## License\n\nMIT © [Loris Guignard](http://github.com/loris)\n\n[npm-url]: https://npmjs.org/package/api-query-params\n[npm-image]: https://img.shields.io/npm/v/api-query-params.svg?style=flat-square\n[travis-url]: https://travis-ci.org/loris/api-query-params\n[travis-image]: https://img.shields.io/travis/loris/api-query-params.svg?style=flat-square\n[coveralls-url]: https://coveralls.io/r/loris/api-query-params\n[coveralls-image]: https://img.shields.io/coveralls/loris/api-query-params.svg?style=flat-square\n[depstat-url]: https://david-dm.org/loris/api-query-params\n[depstat-image]: https://david-dm.org/loris/api-query-params.svg?style=flat-square\n[download-badge]: http://img.shields.io/npm/dm/api-query-params.svg?style=flat-square\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floris%2Fapi-query-params","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Floris%2Fapi-query-params","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floris%2Fapi-query-params/lists"}