npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-query-cg

v0.5.2

Published

fork of mongoose Query lib (mongoose-query)

Downloads

6

Readme

mongoose-query

Build Status Greenkeeper badge JavaScript Style Guide License badge release npm version Stars badge

This library is usefull example with expressjs + mongoose applications to help construct mongoose query model directly from url parameters. Example:

http://localhost/model?q={"group":"users"}&f=name&sk=1&l=5&p=name

Converted to:

model.find({group: "users"}).select("name").skip(1).limit(5).populate('name')

Tested with node.js versions

6.x, 7.x, 8.x, LTS, latest release

Changes log

See releases page.

Installation

Use npm:

npm install mongoose-query

Test

npm test && npm run lint

Usage Example

var QueryPlugin = require(mongoose-query);
var TestSchema = new mongoose.Schema({});
TestSchema.plugin(QueryPlugin);
var testmodel = mongoose.model('test', TestSchema);

//express route
module.exports = function query(req, res) {
  testmodel.query(req.query, function(error, data){
    res.json(error?{error: error}:data);
  });
}

doc

var QueryPlugin = require(mongoose-query);
schema.plugin( QueryPlugin(, <options>) )

optional options:

  • logger: custom logger, e.g. winston logger, default: "dummy logger"
  • allowEval: Allow to use eval or not, default: true
  • includeAllParams: Parse also other values. e.g. ?name=me. default: true
  • ignoreKeys : <array{String}> keys to be ignored. Default: []

Model static methods:

model.query( <query>(, <callback>) )

model.leanQuery(<query>(, <callback>) ): gives plain objects (lean)

Note: without <callback> you get Promise.

URL API:

http://www.myserver.com/query?[q=<query>][&t=<type>][&f=<fields>][&s=<order>][&sk=<skip>]
[&l=<limit>][&p=<populate>][&fl=<boolean>][&map=<mapFunction>][&reduce=<reduceFunction>]

q=<query>                   restrict results by the specified JSON query
                            regex e.g. q='{"field":{"$regex":"/mygrep/", "$options":"i"}}'
t=<type>                    find|findOne|count|aggregate|distinct|aggregate|mapReduce
f=<set of fields>           specify the set of fields to include or exclude in each document
                            (1 - include; 0 - exclude)
s=<sort order>              specify the order in which to sort each specified field
                            (1- ascending; -1 - descending), JSON
sk=<num results to skip>    specify the number of results to skip in the result set;
                            useful for paging
l=<limit>                   specify the limit for the number of results (default is 1000)
p=<populate>                specify the fields for populate, also more complex json object is supported.
map=<mapFunction>           mongodb map function as string
                            http://docs.mongodb.org/manual/reference/command/mapReduce/#mapreduce-map-cmd'
                            e.g. "function(){if (this.status == 'A') emit(this.cust_id, 1);)}"
reduce=<reduceFunction>     mongodb reduce function as string
                            http://docs.mongodb.org/manual/reference/command/mapReduce/#mapreduce-reduce-cmd
                            e.g. "function(key, values) {return result;}"
fl=<boolean>                Flat results or not

Special values:
"oid:<string>"              string is converted to ObjectId
"/regex/(options)"          converted to regex
{ $regex: /<string>/,       regex match with optional regex options
 ($options: "") }        

Alternative search conditions:
"key={i}a"                  case insensitive
"key={e}a"                  ends with a
"key={b}a"                  begins with a
"key={in}a,b"               At least one of these is in array
"key={nin}a,b"              Any of these values is not in array
"key={all}a,b"              All of these contains in array
"key={empty}"               Field is empty or not exists
"key={!empty}"              Field exists and is not empty
"key={mod}a,b"              Docs where key mod a is b
"key={gt}a"                 value is greater than a
"key={gte}a"                value is greater or equal than a
"key={lt}a"                 value is lower than a
"key={lte}a"                value is lower or equal
"key={ne}a"                 value is not equal
"key={size}a"               value is array, and array size is a
"key={sort_by}"             sort by asc
"key={sort_by}-1"           sort by desc

**References to mongo:**
- [elemMatch](https://docs.mongodb.com/manual/reference/operator/query/elemMatch/)
- [size](https://docs.mongodb.com/manual/reference/operator/query/size/)

Results with `fl=false`:

[ { nest: { ed: { data: 'value', data2':'value' } } } ]


Results with `fl=true`:

[ {'nest.ed.data': 'value', 'nest.ed.data2':'value'}, ]



#### Date

Allowed date formats:
- `2010/10/1` (y/m/d)
- `31/2/2010` (d/m/y)
- `2011-10-10T14:48:00` (ISO 8601)

**Note:**
Only valid format is ISO when using date inside `q` -parameter.