Gathering detailed insights and metrics for mquery
Gathering detailed insights and metrics for mquery
Gathering detailed insights and metrics for mquery
Gathering detailed insights and metrics for mquery
express-mquery
Expose mongoose query API through HTTP request
@ecromaneli/mquery
The mQuery (or Mini-jQuery) is a most simple and clean way to query HTML elements and bind Event Handlers without jQuery.
opentsdb-mquery
OpenTSDB metric query generator.
mongoose-rest-actions
mongoose rest actions on top of express
npm install mquery
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
478 Stars
435 Commits
73 Forks
16 Watching
6 Branches
31 Contributors
Updated on 01 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
1.6%
478,994
Compared to previous day
Last week
3.5%
2,630,344
Compared to previous week
Last month
10%
10,654,231
Compared to previous month
Last year
18.4%
114,545,870
Compared to previous year
1
4
mquery
is a fluent mongodb query builder designed to run in multiple environments.
1const mongo = require('mongodb'); 2 3const client = new mongo.MongoClient(uri); 4await client.connect(); 5// get a collection 6const collection = client.collection('artists'); 7 8// pass it to the constructor 9await mquery(collection).find({...}); 10 11// or pass it to the collection method 12const docs = await mquery().find({...}).collection(collection); 13 14// or better yet, create a custom query constructor that has it always set 15const Artist = mquery(collection).toConstructor(); 16const docs = await Artist().find(...).where(...);
mquery
requires a collection object to work with. In the example above we just pass the collection object created using the official MongoDB driver.
Declares this query a find query. Optionally pass a match clause.
1mquery().find() 2mquery().find(match) 3await mquery().find() 4const docs = await mquery().find(match); 5assert(Array.isArray(docs));
Declares this query a findOne query. Optionally pass a match clause.
1mquery().findOne() 2mquery().findOne(match) 3await mquery().findOne() 4const doc = await mquery().findOne(match); 5if (doc) { 6 // the document may not be found 7 console.log(doc); 8}
Declares this query a count query. Optionally pass a match clause.
1mquery().count()
2mquery().count(match)
3await mquery().count()
4const number = await mquery().count(match);
5console.log('we found %d matching documents', number);
Declares this query a findAndModify with update query. Optionally pass a match clause, update document, options.
When executed, the first matching document (if found) is modified according to the update document and passed back.
Options are passed to the setOptions()
method.
returnDocument
: string - 'after'
to return the modified document rather than the original. defaults to 'before'
upsert
: boolean - creates the object if it doesn't exist. defaults to falsesort
: if multiple docs are found by the match condition, sets the sort order to choose which doc to update1query.findOneAndUpdate()
2query.findOneAndUpdate(updateDocument)
3query.findOneAndUpdate(match, updateDocument)
4query.findOneAndUpdate(match, updateDocument, options)
5
6// the following all execute the command
7await query.findOneAndUpdate()
8await query.findOneAndUpdate(updateDocument)
9await query.findOneAndUpdate(match, updateDocument)
10const doc = await await query.findOneAndUpdate(match, updateDocument, options);
11if (doc) {
12 // the document may not be found
13 console.log(doc);
14}
Declares this query a findAndModify with remove query. Alias of findOneAndDelete. Optionally pass a match clause, options.
When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed as a result.
Options are passed to the setOptions()
method.
sort
: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove1A.where().findOneAndDelete() 2A.where().findOneAndRemove() 3A.where().findOneAndRemove(match) 4A.where().findOneAndRemove(match, options) 5 6// the following all execute the command 7await A.where().findOneAndRemove() 8await A.where().findOneAndRemove(match) 9const doc = await A.where().findOneAndRemove(match, options); 10if (doc) { 11 // the document may not be found 12 console.log(doc); 13}
Declares this query a distinct query. Optionally pass the distinct field, a match clause.
1mquery().distinct() 2mquery().distinct(match) 3mquery().distinct(match, field) 4mquery().distinct(field) 5 6// the following all execute the command 7await mquery().distinct() 8await mquery().distinct(field) 9await mquery().distinct(match) 10const result = await mquery().distinct(match, field); 11console.log(result);
Executes the query.
1const docs = await mquery().findOne().where('route').intersects(polygon).exec()
Executes the query and returns a stream.
1var stream = mquery().find().stream(options); 2stream.on('data', cb); 3stream.on('close', fn);
Note: this only works with find()
operations.
Note: returns the stream object directly from the node-mongodb-native driver. (currently streams1 type stream). Any options will be passed along to the driver method.
Specifies an $all
query condition
1mquery().where('permission').all(['read', 'write'])
Specifies arguments for an $and
condition
1mquery().and([{ color: 'green' }, { status: 'ok' }])
Specifies a $box
condition
1var lowerLeft = [40.73083, -73.99756] 2var upperRight= [40.741404, -73.988135] 3 4mquery().where('location').within().box(lowerLeft, upperRight)
Specifies a $center
or $centerSphere
condition.
1var area = { center: [50, 50], radius: 10, unique: true } 2query.where('loc').within().circle(area) 3query.circle('loc', area); 4 5// for spherical calculations 6var area = { center: [50, 50], radius: 10, unique: true, spherical: true } 7query.where('loc').within().circle(area) 8query.circle('loc', area);
Specifies an $elemMatch
condition
1query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) 2 3query.elemMatch('comment', function (elem) { 4 elem.where('author').equals('autobot'); 5 elem.where('votes').gte(5); 6})
Specifies the complementary comparison value for the path specified with where()
.
1mquery().where('age').equals(49); 2 3// is the same as 4 5mquery().where({ 'age': 49 });
Specifies an $exists
condition
1// { name: { $exists: true }} 2mquery().where('name').exists() 3mquery().where('name').exists(true) 4mquery().exists('name') 5 6// { name: { $exists: false }} 7mquery().where('name').exists(false); 8mquery().exists('name', false);
Specifies a $geometry
condition
1var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] 2query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) 3 4// or 5var polyB = [[ 0, 0 ], [ 1, 1 ]] 6query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) 7 8// or 9var polyC = [ 0, 0 ] 10query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) 11 12// or 13query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) 14 15// or 16query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] })
geometry()
must come after intersects()
, within()
, or near()
.
The object
argument must contain type
and coordinates
properties.
String
Array
Specifies a $gt
query condition.
1mquery().where('clicks').gt(999)
Specifies a $gte
query condition.
1mquery().where('clicks').gte(1000)
Specifies an $in
query condition.
1mquery().where('author_id').in([3, 48901, 761])
Declares an $geoIntersects
query for geometry()
.
1query.where('path').intersects().geometry({ 2 type: 'LineString' 3 , coordinates: [[180.0, 11.0], [180, 9.0]] 4}) 5 6// geometry arguments are supported 7query.where('path').intersects({ 8 type: 'LineString' 9 , coordinates: [[180.0, 11.0], [180, 9.0]] 10})
Must be used after where()
.
Specifies a $lt
query condition.
1mquery().where('clicks').lt(50)
Specifies a $lte
query condition.
1mquery().where('clicks').lte(49)
Specifies a $maxDistance
query condition.
1mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5)
Specifies a $mod
condition
1mquery().where('count').mod(2, 0)
Specifies a $ne
query condition.
1mquery().where('status').ne('ok')
Specifies an $nin
query condition.
1mquery().where('author_id').nin([3, 48901, 761])
Specifies arguments for an $nor
condition.
1mquery().nor([{ color: 'green' }, { status: 'ok' }])
Specifies arguments for a $near
or $nearSphere
condition.
These operators return documents sorted by distance.
1query.where('loc').near({ center: [10, 10] }); 2query.where('loc').near({ center: [10, 10], maxDistance: 5 }); 3query.near('loc', { center: [10, 10], maxDistance: 5 }); 4 5// GeoJSON 6query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); 7query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); 8query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); 9 10// For a $nearSphere condition, pass the `spherical` option. 11query.near({ center: [10, 10], maxDistance: 5, spherical: true });
Specifies arguments for an $or
condition.
1mquery().or([{ color: 'red' }, { status: 'emergency' }])
Specifies a $polygon
condition
1mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) 2mquery().polygon('loc', [10,20], [13, 25], [7,15])
Specifies a $regex
query condition.
1mquery().where('name').regex(/^sixstepsrecords/)
Specifies which document fields to include or exclude
1// 1 means include, 0 means exclude 2mquery().select({ name: 1, address: 1, _id: 0 }) 3 4// or 5 6mquery().select('name address -_id')
When passing a string, prefixing a path with -
will flag that path as excluded. When a path does not have the -
prefix, it is included.
1// include a and b, exclude c 2query.select('a b -c'); 3 4// or you may use object notation, useful when 5// you have keys already prefixed with a "-" 6query.select({a: 1, b: 1, c: 0});
Cannot be used with distinct()
.
Determines if the query has selected any fields.
1var query = mquery(); 2query.selected() // false 3query.select('-name'); 4query.selected() // true
Determines if the query has selected any fields inclusively.
1var query = mquery().select('name'); 2query.selectedInclusively() // true 3 4var query = mquery(); 5query.selected() // false 6query.select('-name'); 7query.selectedInclusively() // false 8query.selectedExclusively() // true
Determines if the query has selected any fields exclusively.
1var query = mquery().select('-name'); 2query.selectedExclusively() // true 3 4var query = mquery(); 5query.selected() // false 6query.select('name'); 7query.selectedExclusively() // false 8query.selectedInclusively() // true
Specifies a $size
query condition.
1mquery().where('someArray').size(6)
Specifies a $slice
projection for a path
1mquery().where('comments').slice(5) 2mquery().where('comments').slice(-5) 3mquery().where('comments').slice([-10, 5])
Sets a $geoWithin
or $within
argument for geo-spatial queries.
1mquery().within().box() 2mquery().within().circle() 3mquery().within().geometry() 4 5mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); 6mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); 7mquery().where('loc').within({ polygon: [[],[],[],[]] }); 8 9mquery().where('loc').within([], [], []) // polygon 10mquery().where('loc').within([], []) // box 11mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
As of mquery 2.0, $geoWithin
is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see mquery.use$geoWithin.
Must be used after where()
.
Specifies a path
for use with chaining
1// instead of writing: 2mquery().find({age: {$gte: 21, $lte: 65}}); 3 4// we can instead write: 5mquery().where('age').gte(21).lte(65); 6 7// passing query conditions is permitted too 8mquery().find().where({ name: 'vonderful' }) 9 10// chaining 11await mquery() 12 .where('age').gte(21).lte(65) 13 .where({ 'name': /^vonderful/i }) 14 .where('friends').slice(10) 15 .exec()
Specifies a $where
condition.
Use $where
when you need to select documents using a JavaScript expression.
1await query.$where('this.comments.length > 10 || this.name.length > 5').exec() 2 3query.$where(function () { 4 return this.comments.length > 10 || this.name.length > 5; 5})
Only use $where
when you have a condition that cannot be met using other MongoDB operators like $lt
. Be sure to read about all of its caveats before using.
Specifies the batchSize option.
1query.batchSize(100)
Cannot be used with distinct()
.
Specifies the collation option.
1query.collation({ locale: "en_US", strength: 1 })
Specifies the comment option.
1query.comment('login query');
Cannot be used with distinct()
.
Sets query hints.
1mquery().hint({ indexA: 1, indexB: -1 })
Cannot be used with distinct()
.
Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal.
This option is only valid for operations that write to the database:
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndUpdate()
updateOne()
updateMany()
Defaults to the j
value if it is specified in writeConcern
1mquery().j(true);
Specifies the limit option.
1query.limit(20)
Cannot be used with distinct()
.
Specifies the maxTimeMS option.
1query.maxTime(100) 2query.maxTimeMS(100)
Specifies the skip option.
1query.skip(100).limit(20)
Cannot be used with distinct()
.
Sets the query sort order.
If an object is passed, key values allowed are asc
, desc
, ascending
, descending
, 1
, and -1
.
If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with -
which will be treated as descending.
1// these are equivalent 2query.sort({ field: 'asc', test: -1 }); 3query.sort('field -test');
Cannot be used with distinct()
.
Sets the readPreference option for the query.
1mquery().read('primary') 2mquery().read('p') // same as primary 3 4mquery().read('primaryPreferred') 5mquery().read('pp') // same as primaryPreferred 6 7mquery().read('secondary') 8mquery().read('s') // same as secondary 9 10mquery().read('secondaryPreferred') 11mquery().read('sp') // same as secondaryPreferred 12 13mquery().read('nearest') 14mquery().read('n') // same as nearest 15 16mquery().setReadPreference('primary') // alias of .read()
primary
- (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.secondary
- Read from secondary if available, otherwise error.primaryPreferred
- Read from primary if available, otherwise a secondary.secondaryPreferred
- Read from a secondary if available, otherwise read from the primary.nearest
- All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.Aliases
p
primarypp
primaryPreferreds
secondarysp
secondaryPreferredn
nearestTo keep the separation of concerns between mquery
and your driver
clean, mquery#read()
no longer handles specifying a second tags
argument as of version 0.5.
If you need to specify tags, pass any non-string argument as the first argument.
mquery
will pass this argument untouched to your collections methods later.
For example:
1// example of specifying tags using the Node.js driver 2var ReadPref = require('mongodb').ReadPreference; 3var preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); 4mquery(...).read(preference).exec();
Read more about how to use read preferences here and here.
Sets the readConcern option for the query.
1// local 2mquery().readConcern('local') 3mquery().readConcern('l') 4mquery().r('l') 5 6// available 7mquery().readConcern('available') 8mquery().readConcern('a') 9mquery().r('a') 10 11// majority 12mquery().readConcern('majority') 13mquery().readConcern('m') 14mquery().r('m') 15 16// linearizable 17mquery().readConcern('linearizable') 18mquery().readConcern('lz') 19mquery().r('lz') 20 21// snapshot 22mquery().readConcern('snapshot') 23mquery().readConcern('s') 24mquery().r('s')
local
- The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.2+)available
- The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.6+)majority
- The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. (MongoDB 3.2+)linearizable
- The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. (MongoDB 3.4+)snapshot
- Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. (MongoDB 4.0+)Aliases
l
locala
availablem
majoritylz
linearizables
snapshotRead more about how to use read concern here.
Sets the writeConcern option for the query.
This option is only valid for operations that write to the database:
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndUpdate()
updateOne()
updateMany()
1mquery().writeConcern(0) 2mquery().writeConcern(1) 3mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) 4mquery().writeConcern('majority') 5mquery().writeConcern('m') // same as majority 6mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead 7mquery().w(1) // w is alias of writeConcern
writeConcern({ w: <value>
, j: <boolean>
, wtimeout: <number>
}`)
Can be break down to use the following syntax:
mquery().w(<value>
).j(<boolean>
).wtimeout(<number>
)
Read more about how to use write concern here
Sets the slaveOk option. true
allows reading from secondaries.
deprecated use read() preferences instead if on mongodb >= 2.2
1query.slaveOk() // true 2query.slaveOk(true) 3query.slaveOk(false)
Sets tailable option.
1mquery().tailable() <== true 2mquery().tailable(true) 3mquery().tailable(false)
Cannot be used with distinct()
.
Specifies a time limit, in milliseconds, for the write concern. If w > 1
, it is maximum amount of time to
wait for this write to propagate through the replica set before this operation fails. The default is 0
, which means no timeout.
This option is only valid for operations that write to the database:
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndUpdate()
updateOne()
updateMany()
Defaults to wtimeout
value if it is specified in writeConcern
1mquery().wtimeout(2000) 2mquery().wTimeout(2000)
Sets the querys collection.
1mquery().collection(aCollection)
Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error.
1mquery().find(..).then(success, error);
This is very useful when combined with co or koa, which automatically resolve promise-like objects for you.
1co(function*(){ 2 var doc = yield mquery().findOne({ _id: 499 }); 3 console.log(doc); // { _id: 499, name: 'amazing', .. } 4})();
NOTE:
The returned promise is a bluebird promise but this is customizable. If you want to
use your favorite promise library, simply set mquery.Promise = YourPromiseConstructor
.
Your Promise
must be promises A+ compliant.
Merges other mquery or match condition objects into this one. When an mquery instance is passed, its match conditions, field selection and options are merged.
1const drum = mquery({ type: 'drum' }).collection(instruments); 2const redDrum = mquery({ color: 'red' }).merge(drum); 3const n = await redDrum.count(); 4console.log('there are %d red drums', n);
Internally uses mquery.canMerge
to determine validity.
Sets query options.
1mquery().setOptions({ collection: coll, limit: 20 })
* denotes a query helper method is also available
Set a function to trace this query. Useful for profiling or logging.
1function traceFunction (method, queryInfo, query) { 2 console.log('starting ' + method + ' query'); 3 4 return function (err, result, millis) { 5 console.log('finished ' + method + ' query in ' + millis + 'ms'); 6 }; 7} 8 9mquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb);
The trace function is passed (method, queryInfo, query)
The trace function should return a callback function which accepts:
NOTE: stream requests are not traced.
Similar to setTraceFunction()
but automatically applied to all queries.
1mquery.setTraceFunction(traceFunction);
Determines if conditions
can be merged using mquery().merge()
.
1var query = mquery({ type: 'drum' }); 2var okToMerge = mquery.canMerge(anObject) 3if (okToMerge) { 4 query.merge(anObject); 5}
MongoDB 2.4 introduced the $geoWithin
operator which replaces and is 100% backward compatible with $within
. As of mquery 0.2, we default to using $geoWithin
for all within()
calls.
If you are running MongoDB < 2.4 this will be problematic. To force mquery
to be backward compatible and always use $within
, set the mquery.use$geoWithin
flag to false
.
1mquery.use$geoWithin = false;
Often times we want custom base queries that encapsulate predefined criteria. With mquery
this is easy. First create the query you want to reuse and call its toConstructor()
method which returns a new subclass of mquery
that retains all options and criteria of the original.
1var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); 2 3// use it! 4const n = await greatMovies().count(); 5console.log('There are %d great movies', n); 6 7const docs = await greatMovies().where({ name: /^Life/ }).select('name').find(); 8console.log(docs);
Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a distinct
query does not support specifying options like hint
or field selection. In this case an error will be thrown so you can catch these mistakes in development.
Debug mode is provided through the use of the debug module. To enable:
1DEBUG=mquery node yourprogram.js
Read the debug module documentation for more details.
mquery
clones query arguments before passing them to a collection
method for execution.
This prevents accidental side-affects to the objects you pass.
To clone ObjectIds
we need to make some assumptions.
First, to check if an object is an ObjectId
, we check its constructors name. If it matches either
ObjectId
or ObjectID
we clone it.
To clone ObjectIds
, we call its optional clone
method. If a clone
method does not exist, we fall
back to calling new obj.constructor(obj.id)
. We assume, for compatibility with the
Node.js driver, that the ObjectId
instance has a public id
property and that
when creating an ObjectId
instance we can pass that id
as an argument.
mquery
supports specifying Read Preferences to control from which MongoDB node your query will read.
The Read Preferences spec also support specifying tags. To pass tags, some
drivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags.
If you need to specify tags, pass an instance of your drivers ReadPreference constructor or roll your own. mquery
will store whatever you provide and pass later to your collection during execution.
1npm install mquery
The latest stable version of the package.
Stable Version
1
5.3/10
Summary
Code Injection in mquery
Affected Versions
< 3.2.3
Patched Versions
3.2.3
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 3/5 approved changesets -- score normalized to 6
Reason
dependency not pinned by hash detected -- score normalized to 6
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More