get-query-modifier
Helper for parsing mongoose mongodb query operators.
What is this?
get-query-modifier is a module designed to help with mongoose query parsing.
Let's say you have a GET /api/comments
endpoint, in your API like the
following:
app;
Suddenly, you decided to add pagination to this route. You could easily
implement calls with mongoose's Query.prototype.limit
and
Query.prototype.skip
, as follows:
app;
Or something like that.
You'd be, however, recreating your own query syntax.
You can get a lot more power by using mongodb's default query syntax,
extending it where mongoose/mongodb expose a slightly different API, such
as .limit
, .skip
etc.
get-query-modifier solves this solution by extracting the operators
$sort
, $limit
, $skip
, $page
and $select
(plus any operator you want to
support by setting options.allow
), and translating them into a set of method
calls to the query object (calls to Query.prototype.sort
,
Query.prototype.select
etc.). This allows maximum flexibility for using both
the req.query
object for further querying in the mongoose API and supporting a
known standard set of operators, which come out-of-the-box in mongodb.
It does it by taking the query object as its first argument and returning a
modifier function, which handles calling each of these deferred Query
method
calls once your Query
instance is available.
app;
getQueryModifier(query, [options])
Manipulates an object representation of a querystring, extracting its
mongoose
query operators and returning a function to attach them to a
mongoose.Query
object.
Note this function isn't pure and does delete the operators from the query
parameter after reading them.
Params:
- Object query The querystring representation to manipulate
- Object [options] An options object
- Object [options.defaults] An object with defaults for the valid operators
- Object [options.ignore] An object with the properties corresponding to the ignored operators set to true
- Boolean [options.deleteIgnored=false] Whether to delete the ignored
operators from the
query
object - Array. [options.allow] An array of operators to parse in
addition to the plugin's default
VALID_OPERATORS.
Return:
- Function queryModifier The
mongoose.Query
modifier function, which attaches the operators to the search
Example:
var app = ; // some express appvar mongoose = ;var User = mongoose; // some mongoose model app;
See the tests for more elaborate examples.
getQueryModifier.middleware([options])
A connect middleware for parsing and using mongodb query operators with mongoose given an object representation of a query.
Params:
- Object [options] An options object which will simply be passed onto
getQueryModifier(req.query, options)
Return:
- Function mdw The middleware function
Example:
var app = ; // some express appapp;
License
This code is licensed under the MIT License. See LICENSE for more information.