Middleware to transform query strings in a format that is recognized by the MongoDB, MySQL¹ and other databases.
To ensure the smooth operation of the middleware, your web application must be built using the express.js or hapi.js frameworks.
Use the npm command to install this library into your project:
npm i --save query-strings-parser
const express = require('express')
const qs = require('query-strings-parser')
const app = express()
app.use(qs()) // middleware query-strings-parser
app.listen(3000, (req, res) => {
console.log('app listening on port 3000')
})
app.get('/', (req, res) => {
res.send('the query is:' + JSON.stringify(req.query))
})
/**
* Request: http://localhost:3000?fields=name,age&skip=10&limit=10&sort=created_at
* Result (req.query):
* {
* fields: { name: 1, age: 1 },
* sort: { created_at: 'asc' }
* filters: {},
* pagination: {
* skip: 10,
* limit: 10
* },
* original: '?fields=name,age&skip=10&limit=10&sort=created_at'
* }
*/
options = {
use_page: false,
client_db: 'mongodb',
date_field: {
start_at: 'created_at',
end_at: 'created_at'
},
default: {
fields: {},
sort: {},
filters: {},
pagination: {
limit: Number.MAX_SAFE_INTEGER,
skip: 0,
page: 1
}
}
}
If the options are not provided, the default values will be used for the treatment of queries strings.
const express = require('express')
const qs = require('query-strings-parser')
const app = express()
app.use(qs({
use_page: true,
client_db: 'mongodb',
date_field: {
start_at: 'timestamp',
end_at: 'timestamp'
},
default: {
fields: {name: 1 , age: 1, number: 1, _id: 0},
sort: { created_at: 'desc' },
filters: {},
pagination: {
page: 1,
limit: 100
}
}
}))
/**
* Request: http://localhost:3000?fields=name,age&age=30
* Result (req.query):
* {
* fields: { name: 1, age: 1},
* sort: { created_at: 'desc' }
* filters: {age: 30},
* pagination: {
* limit: 100,
* page: 1
* },
* original: '?fields=name,age&age=30'
* }
*/
For more details, access the wiki page.
For informations and details about the supported query strings, access the wiki page.
- Support for parser functions. For informations and details about parser functions, access the wiki page.
- ¹Support for relational databases such as MySQL, PostgreSQL and SQLite.