mquery.js 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252
  1. 'use strict';
  2. /**
  3. * Dependencies
  4. */
  5. var slice = require('sliced');
  6. var assert = require('assert');
  7. var util = require('util');
  8. var utils = require('./utils');
  9. var debug = require('debug')('mquery');
  10. /* global Map */
  11. /**
  12. * Query constructor used for building queries.
  13. *
  14. * ####Example:
  15. *
  16. * var query = new Query({ name: 'mquery' });
  17. * query.setOptions({ collection: moduleCollection })
  18. * query.where('age').gte(21).exec(callback);
  19. *
  20. * @param {Object} [criteria]
  21. * @param {Object} [options]
  22. * @api public
  23. */
  24. function Query(criteria, options) {
  25. if (!(this instanceof Query))
  26. return new Query(criteria, options);
  27. var proto = this.constructor.prototype;
  28. this.op = proto.op || undefined;
  29. this.options = Object.assign({}, proto.options);
  30. this._conditions = proto._conditions
  31. ? utils.clone(proto._conditions)
  32. : {};
  33. this._fields = proto._fields
  34. ? utils.clone(proto._fields)
  35. : undefined;
  36. this._update = proto._update
  37. ? utils.clone(proto._update)
  38. : undefined;
  39. this._path = proto._path || undefined;
  40. this._distinct = proto._distinct || undefined;
  41. this._collection = proto._collection || undefined;
  42. this._traceFunction = proto._traceFunction || undefined;
  43. if (options) {
  44. this.setOptions(options);
  45. }
  46. if (criteria) {
  47. if (criteria.find && criteria.remove && criteria.update) {
  48. // quack quack!
  49. this.collection(criteria);
  50. } else {
  51. this.find(criteria);
  52. }
  53. }
  54. }
  55. /**
  56. * This is a parameter that the user can set which determines if mquery
  57. * uses $within or $geoWithin for queries. It defaults to true which
  58. * means $geoWithin will be used. If using MongoDB < 2.4 you should
  59. * set this to false.
  60. *
  61. * @api public
  62. * @property use$geoWithin
  63. */
  64. var $withinCmd = '$geoWithin';
  65. Object.defineProperty(Query, 'use$geoWithin', {
  66. get: function( ) { return $withinCmd == '$geoWithin'; },
  67. set: function(v) {
  68. if (true === v) {
  69. // mongodb >= 2.4
  70. $withinCmd = '$geoWithin';
  71. } else {
  72. $withinCmd = '$within';
  73. }
  74. }
  75. });
  76. /**
  77. * Converts this query to a constructor function with all arguments and options retained.
  78. *
  79. * ####Example
  80. *
  81. * // Create a query that will read documents with a "video" category from
  82. * // `aCollection` on the primary node in the replica-set unless it is down,
  83. * // in which case we'll read from a secondary node.
  84. * var query = mquery({ category: 'video' })
  85. * query.setOptions({ collection: aCollection, read: 'primaryPreferred' });
  86. *
  87. * // create a constructor based off these settings
  88. * var Video = query.toConstructor();
  89. *
  90. * // Video is now a subclass of mquery() and works the same way but with the
  91. * // default query parameters and options set.
  92. *
  93. * // run a query with the previous settings but filter for movies with names
  94. * // that start with "Life".
  95. * Video().where({ name: /^Life/ }).exec(cb);
  96. *
  97. * @return {Query} new Query
  98. * @api public
  99. */
  100. Query.prototype.toConstructor = function toConstructor() {
  101. function CustomQuery(criteria, options) {
  102. if (!(this instanceof CustomQuery))
  103. return new CustomQuery(criteria, options);
  104. Query.call(this, criteria, options);
  105. }
  106. utils.inherits(CustomQuery, Query);
  107. // set inherited defaults
  108. var p = CustomQuery.prototype;
  109. p.options = {};
  110. p.setOptions(this.options);
  111. p.op = this.op;
  112. p._conditions = utils.clone(this._conditions);
  113. p._fields = utils.clone(this._fields);
  114. p._update = utils.clone(this._update);
  115. p._path = this._path;
  116. p._distinct = this._distinct;
  117. p._collection = this._collection;
  118. p._traceFunction = this._traceFunction;
  119. return CustomQuery;
  120. };
  121. /**
  122. * Sets query options.
  123. *
  124. * ####Options:
  125. *
  126. * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) *
  127. * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) *
  128. * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) *
  129. * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) *
  130. * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) *
  131. * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) *
  132. * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) *
  133. * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) *
  134. * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) *
  135. * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) *
  136. * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) *
  137. * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command)
  138. * - collection the collection to query against
  139. *
  140. * _* denotes a query helper method is also available_
  141. *
  142. * @param {Object} options
  143. * @api public
  144. */
  145. Query.prototype.setOptions = function(options) {
  146. if (!(options && utils.isObject(options)))
  147. return this;
  148. // set arbitrary options
  149. var methods = utils.keys(options),
  150. method;
  151. for (var i = 0; i < methods.length; ++i) {
  152. method = methods[i];
  153. // use methods if exist (safer option manipulation)
  154. if ('function' == typeof this[method]) {
  155. var args = utils.isArray(options[method])
  156. ? options[method]
  157. : [options[method]];
  158. this[method].apply(this, args);
  159. } else {
  160. this.options[method] = options[method];
  161. }
  162. }
  163. return this;
  164. };
  165. /**
  166. * Sets this Querys collection.
  167. *
  168. * @param {Collection} coll
  169. * @return {Query} this
  170. */
  171. Query.prototype.collection = function collection(coll) {
  172. this._collection = new Query.Collection(coll);
  173. return this;
  174. };
  175. /**
  176. * Adds a collation to this op (MongoDB 3.4 and up)
  177. *
  178. * ####Example
  179. *
  180. * query.find().collation({ locale: "en_US", strength: 1 })
  181. *
  182. * @param {Object} value
  183. * @return {Query} this
  184. * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation
  185. * @api public
  186. */
  187. Query.prototype.collation = function(value) {
  188. this.options.collation = value;
  189. return this;
  190. };
  191. /**
  192. * Specifies a `$where` condition
  193. *
  194. * Use `$where` when you need to select documents using a JavaScript expression.
  195. *
  196. * ####Example
  197. *
  198. * query.$where('this.comments.length > 10 || this.name.length > 5')
  199. *
  200. * query.$where(function () {
  201. * return this.comments.length > 10 || this.name.length > 5;
  202. * })
  203. *
  204. * @param {String|Function} js javascript string or function
  205. * @return {Query} this
  206. * @memberOf Query
  207. * @method $where
  208. * @api public
  209. */
  210. Query.prototype.$where = function(js) {
  211. this._conditions.$where = js;
  212. return this;
  213. };
  214. /**
  215. * Specifies a `path` for use with chaining.
  216. *
  217. * ####Example
  218. *
  219. * // instead of writing:
  220. * User.find({age: {$gte: 21, $lte: 65}}, callback);
  221. *
  222. * // we can instead write:
  223. * User.where('age').gte(21).lte(65);
  224. *
  225. * // passing query conditions is permitted
  226. * User.find().where({ name: 'vonderful' })
  227. *
  228. * // chaining
  229. * User
  230. * .where('age').gte(21).lte(65)
  231. * .where('name', /^vonderful/i)
  232. * .where('friends').slice(10)
  233. * .exec(callback)
  234. *
  235. * @param {String} [path]
  236. * @param {Object} [val]
  237. * @return {Query} this
  238. * @api public
  239. */
  240. Query.prototype.where = function() {
  241. if (!arguments.length) return this;
  242. if (!this.op) this.op = 'find';
  243. var type = typeof arguments[0];
  244. if ('string' == type) {
  245. this._path = arguments[0];
  246. if (2 === arguments.length) {
  247. this._conditions[this._path] = arguments[1];
  248. }
  249. return this;
  250. }
  251. if ('object' == type && !Array.isArray(arguments[0])) {
  252. return this.merge(arguments[0]);
  253. }
  254. throw new TypeError('path must be a string or object');
  255. };
  256. /**
  257. * Specifies the complementary comparison value for paths specified with `where()`
  258. *
  259. * ####Example
  260. *
  261. * User.where('age').equals(49);
  262. *
  263. * // is the same as
  264. *
  265. * User.where('age', 49);
  266. *
  267. * @param {Object} val
  268. * @return {Query} this
  269. * @api public
  270. */
  271. Query.prototype.equals = function equals(val) {
  272. this._ensurePath('equals');
  273. var path = this._path;
  274. this._conditions[path] = val;
  275. return this;
  276. };
  277. /**
  278. * Specifies the complementary comparison value for paths specified with `where()`
  279. * This is alias of `equals`
  280. *
  281. * ####Example
  282. *
  283. * User.where('age').eq(49);
  284. *
  285. * // is the same as
  286. *
  287. * User.shere('age').equals(49);
  288. *
  289. * // is the same as
  290. *
  291. * User.where('age', 49);
  292. *
  293. * @param {Object} val
  294. * @return {Query} this
  295. * @api public
  296. */
  297. Query.prototype.eq = function eq(val) {
  298. this._ensurePath('eq');
  299. var path = this._path;
  300. this._conditions[path] = val;
  301. return this;
  302. };
  303. /**
  304. * Specifies arguments for an `$or` condition.
  305. *
  306. * ####Example
  307. *
  308. * query.or([{ color: 'red' }, { status: 'emergency' }])
  309. *
  310. * @param {Array} array array of conditions
  311. * @return {Query} this
  312. * @api public
  313. */
  314. Query.prototype.or = function or(array) {
  315. var or = this._conditions.$or || (this._conditions.$or = []);
  316. if (!utils.isArray(array)) array = [array];
  317. or.push.apply(or, array);
  318. return this;
  319. };
  320. /**
  321. * Specifies arguments for a `$nor` condition.
  322. *
  323. * ####Example
  324. *
  325. * query.nor([{ color: 'green' }, { status: 'ok' }])
  326. *
  327. * @param {Array} array array of conditions
  328. * @return {Query} this
  329. * @api public
  330. */
  331. Query.prototype.nor = function nor(array) {
  332. var nor = this._conditions.$nor || (this._conditions.$nor = []);
  333. if (!utils.isArray(array)) array = [array];
  334. nor.push.apply(nor, array);
  335. return this;
  336. };
  337. /**
  338. * Specifies arguments for a `$and` condition.
  339. *
  340. * ####Example
  341. *
  342. * query.and([{ color: 'green' }, { status: 'ok' }])
  343. *
  344. * @see $and http://docs.mongodb.org/manual/reference/operator/and/
  345. * @param {Array} array array of conditions
  346. * @return {Query} this
  347. * @api public
  348. */
  349. Query.prototype.and = function and(array) {
  350. var and = this._conditions.$and || (this._conditions.$and = []);
  351. if (!Array.isArray(array)) array = [array];
  352. and.push.apply(and, array);
  353. return this;
  354. };
  355. /**
  356. * Specifies a $gt query condition.
  357. *
  358. * When called with one argument, the most recent path passed to `where()` is used.
  359. *
  360. * ####Example
  361. *
  362. * Thing.find().where('age').gt(21)
  363. *
  364. * // or
  365. * Thing.find().gt('age', 21)
  366. *
  367. * @method gt
  368. * @memberOf Query
  369. * @param {String} [path]
  370. * @param {Number} val
  371. * @api public
  372. */
  373. /**
  374. * Specifies a $gte query condition.
  375. *
  376. * When called with one argument, the most recent path passed to `where()` is used.
  377. *
  378. * @method gte
  379. * @memberOf Query
  380. * @param {String} [path]
  381. * @param {Number} val
  382. * @api public
  383. */
  384. /**
  385. * Specifies a $lt query condition.
  386. *
  387. * When called with one argument, the most recent path passed to `where()` is used.
  388. *
  389. * @method lt
  390. * @memberOf Query
  391. * @param {String} [path]
  392. * @param {Number} val
  393. * @api public
  394. */
  395. /**
  396. * Specifies a $lte query condition.
  397. *
  398. * When called with one argument, the most recent path passed to `where()` is used.
  399. *
  400. * @method lte
  401. * @memberOf Query
  402. * @param {String} [path]
  403. * @param {Number} val
  404. * @api public
  405. */
  406. /**
  407. * Specifies a $ne query condition.
  408. *
  409. * When called with one argument, the most recent path passed to `where()` is used.
  410. *
  411. * @method ne
  412. * @memberOf Query
  413. * @param {String} [path]
  414. * @param {Number} val
  415. * @api public
  416. */
  417. /**
  418. * Specifies an $in query condition.
  419. *
  420. * When called with one argument, the most recent path passed to `where()` is used.
  421. *
  422. * @method in
  423. * @memberOf Query
  424. * @param {String} [path]
  425. * @param {Number} val
  426. * @api public
  427. */
  428. /**
  429. * Specifies an $nin query condition.
  430. *
  431. * When called with one argument, the most recent path passed to `where()` is used.
  432. *
  433. * @method nin
  434. * @memberOf Query
  435. * @param {String} [path]
  436. * @param {Number} val
  437. * @api public
  438. */
  439. /**
  440. * Specifies an $all query condition.
  441. *
  442. * When called with one argument, the most recent path passed to `where()` is used.
  443. *
  444. * @method all
  445. * @memberOf Query
  446. * @param {String} [path]
  447. * @param {Number} val
  448. * @api public
  449. */
  450. /**
  451. * Specifies a $size query condition.
  452. *
  453. * When called with one argument, the most recent path passed to `where()` is used.
  454. *
  455. * @method size
  456. * @memberOf Query
  457. * @param {String} [path]
  458. * @param {Number} val
  459. * @api public
  460. */
  461. /**
  462. * Specifies a $regex query condition.
  463. *
  464. * When called with one argument, the most recent path passed to `where()` is used.
  465. *
  466. * @method regex
  467. * @memberOf Query
  468. * @param {String} [path]
  469. * @param {String|RegExp} val
  470. * @api public
  471. */
  472. /**
  473. * Specifies a $maxDistance query condition.
  474. *
  475. * When called with one argument, the most recent path passed to `where()` is used.
  476. *
  477. * @method maxDistance
  478. * @memberOf Query
  479. * @param {String} [path]
  480. * @param {Number} val
  481. * @api public
  482. */
  483. /*!
  484. * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance
  485. *
  486. * Thing.where('type').nin(array)
  487. */
  488. 'gt gte lt lte ne in nin all regex size maxDistance minDistance'.split(' ').forEach(function($conditional) {
  489. Query.prototype[$conditional] = function() {
  490. var path, val;
  491. if (1 === arguments.length) {
  492. this._ensurePath($conditional);
  493. val = arguments[0];
  494. path = this._path;
  495. } else {
  496. val = arguments[1];
  497. path = arguments[0];
  498. }
  499. var conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ?
  500. this._conditions[path] :
  501. (this._conditions[path] = {});
  502. conds['$' + $conditional] = val;
  503. return this;
  504. };
  505. });
  506. /**
  507. * Specifies a `$mod` condition
  508. *
  509. * @param {String} [path]
  510. * @param {Number} val
  511. * @return {Query} this
  512. * @api public
  513. */
  514. Query.prototype.mod = function() {
  515. var val, path;
  516. if (1 === arguments.length) {
  517. this._ensurePath('mod');
  518. val = arguments[0];
  519. path = this._path;
  520. } else if (2 === arguments.length && !utils.isArray(arguments[1])) {
  521. this._ensurePath('mod');
  522. val = slice(arguments);
  523. path = this._path;
  524. } else if (3 === arguments.length) {
  525. val = slice(arguments, 1);
  526. path = arguments[0];
  527. } else {
  528. val = arguments[1];
  529. path = arguments[0];
  530. }
  531. var conds = this._conditions[path] || (this._conditions[path] = {});
  532. conds.$mod = val;
  533. return this;
  534. };
  535. /**
  536. * Specifies an `$exists` condition
  537. *
  538. * ####Example
  539. *
  540. * // { name: { $exists: true }}
  541. * Thing.where('name').exists()
  542. * Thing.where('name').exists(true)
  543. * Thing.find().exists('name')
  544. *
  545. * // { name: { $exists: false }}
  546. * Thing.where('name').exists(false);
  547. * Thing.find().exists('name', false);
  548. *
  549. * @param {String} [path]
  550. * @param {Number} val
  551. * @return {Query} this
  552. * @api public
  553. */
  554. Query.prototype.exists = function() {
  555. var path, val;
  556. if (0 === arguments.length) {
  557. this._ensurePath('exists');
  558. path = this._path;
  559. val = true;
  560. } else if (1 === arguments.length) {
  561. if ('boolean' === typeof arguments[0]) {
  562. this._ensurePath('exists');
  563. path = this._path;
  564. val = arguments[0];
  565. } else {
  566. path = arguments[0];
  567. val = true;
  568. }
  569. } else if (2 === arguments.length) {
  570. path = arguments[0];
  571. val = arguments[1];
  572. }
  573. var conds = this._conditions[path] || (this._conditions[path] = {});
  574. conds.$exists = val;
  575. return this;
  576. };
  577. /**
  578. * Specifies an `$elemMatch` condition
  579. *
  580. * ####Example
  581. *
  582. * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
  583. *
  584. * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
  585. *
  586. * query.elemMatch('comment', function (elem) {
  587. * elem.where('author').equals('autobot');
  588. * elem.where('votes').gte(5);
  589. * })
  590. *
  591. * query.where('comment').elemMatch(function (elem) {
  592. * elem.where({ author: 'autobot' });
  593. * elem.where('votes').gte(5);
  594. * })
  595. *
  596. * @param {String|Object|Function} path
  597. * @param {Object|Function} criteria
  598. * @return {Query} this
  599. * @api public
  600. */
  601. Query.prototype.elemMatch = function() {
  602. if (null == arguments[0])
  603. throw new TypeError('Invalid argument');
  604. var fn, path, criteria;
  605. if ('function' === typeof arguments[0]) {
  606. this._ensurePath('elemMatch');
  607. path = this._path;
  608. fn = arguments[0];
  609. } else if (utils.isObject(arguments[0])) {
  610. this._ensurePath('elemMatch');
  611. path = this._path;
  612. criteria = arguments[0];
  613. } else if ('function' === typeof arguments[1]) {
  614. path = arguments[0];
  615. fn = arguments[1];
  616. } else if (arguments[1] && utils.isObject(arguments[1])) {
  617. path = arguments[0];
  618. criteria = arguments[1];
  619. } else {
  620. throw new TypeError('Invalid argument');
  621. }
  622. if (fn) {
  623. criteria = new Query;
  624. fn(criteria);
  625. criteria = criteria._conditions;
  626. }
  627. var conds = this._conditions[path] || (this._conditions[path] = {});
  628. conds.$elemMatch = criteria;
  629. return this;
  630. };
  631. // Spatial queries
  632. /**
  633. * Sugar for geo-spatial queries.
  634. *
  635. * ####Example
  636. *
  637. * query.within().box()
  638. * query.within().circle()
  639. * query.within().geometry()
  640. *
  641. * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
  642. * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
  643. * query.where('loc').within({ polygon: [[],[],[],[]] });
  644. *
  645. * query.where('loc').within([], [], []) // polygon
  646. * query.where('loc').within([], []) // box
  647. * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
  648. *
  649. * ####NOTE:
  650. *
  651. * Must be used after `where()`.
  652. *
  653. * @memberOf Query
  654. * @return {Query} this
  655. * @api public
  656. */
  657. Query.prototype.within = function within() {
  658. // opinionated, must be used after where
  659. this._ensurePath('within');
  660. this._geoComparison = $withinCmd;
  661. if (0 === arguments.length) {
  662. return this;
  663. }
  664. if (2 === arguments.length) {
  665. return this.box.apply(this, arguments);
  666. } else if (2 < arguments.length) {
  667. return this.polygon.apply(this, arguments);
  668. }
  669. var area = arguments[0];
  670. if (!area)
  671. throw new TypeError('Invalid argument');
  672. if (area.center)
  673. return this.circle(area);
  674. if (area.box)
  675. return this.box.apply(this, area.box);
  676. if (area.polygon)
  677. return this.polygon.apply(this, area.polygon);
  678. if (area.type && area.coordinates)
  679. return this.geometry(area);
  680. throw new TypeError('Invalid argument');
  681. };
  682. /**
  683. * Specifies a $box condition
  684. *
  685. * ####Example
  686. *
  687. * var lowerLeft = [40.73083, -73.99756]
  688. * var upperRight= [40.741404, -73.988135]
  689. *
  690. * query.where('loc').within().box(lowerLeft, upperRight)
  691. * query.box('loc', lowerLeft, upperRight )
  692. *
  693. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  694. * @see Query#within #query_Query-within
  695. * @param {String} path
  696. * @param {Object} val
  697. * @return {Query} this
  698. * @api public
  699. */
  700. Query.prototype.box = function() {
  701. var path, box;
  702. if (3 === arguments.length) {
  703. // box('loc', [], [])
  704. path = arguments[0];
  705. box = [arguments[1], arguments[2]];
  706. } else if (2 === arguments.length) {
  707. // box([], [])
  708. this._ensurePath('box');
  709. path = this._path;
  710. box = [arguments[0], arguments[1]];
  711. } else {
  712. throw new TypeError('Invalid argument');
  713. }
  714. var conds = this._conditions[path] || (this._conditions[path] = {});
  715. conds[this._geoComparison || $withinCmd] = { '$box': box };
  716. return this;
  717. };
  718. /**
  719. * Specifies a $polygon condition
  720. *
  721. * ####Example
  722. *
  723. * query.where('loc').within().polygon([10,20], [13, 25], [7,15])
  724. * query.polygon('loc', [10,20], [13, 25], [7,15])
  725. *
  726. * @param {String|Array} [path]
  727. * @param {Array|Object} [val]
  728. * @return {Query} this
  729. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  730. * @api public
  731. */
  732. Query.prototype.polygon = function() {
  733. var val, path;
  734. if ('string' == typeof arguments[0]) {
  735. // polygon('loc', [],[],[])
  736. path = arguments[0];
  737. val = slice(arguments, 1);
  738. } else {
  739. // polygon([],[],[])
  740. this._ensurePath('polygon');
  741. path = this._path;
  742. val = slice(arguments);
  743. }
  744. var conds = this._conditions[path] || (this._conditions[path] = {});
  745. conds[this._geoComparison || $withinCmd] = { '$polygon': val };
  746. return this;
  747. };
  748. /**
  749. * Specifies a $center or $centerSphere condition.
  750. *
  751. * ####Example
  752. *
  753. * var area = { center: [50, 50], radius: 10, unique: true }
  754. * query.where('loc').within().circle(area)
  755. * query.center('loc', area);
  756. *
  757. * // for spherical calculations
  758. * var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
  759. * query.where('loc').within().circle(area)
  760. * query.center('loc', area);
  761. *
  762. * @param {String} [path]
  763. * @param {Object} area
  764. * @return {Query} this
  765. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  766. * @api public
  767. */
  768. Query.prototype.circle = function() {
  769. var path, val;
  770. if (1 === arguments.length) {
  771. this._ensurePath('circle');
  772. path = this._path;
  773. val = arguments[0];
  774. } else if (2 === arguments.length) {
  775. path = arguments[0];
  776. val = arguments[1];
  777. } else {
  778. throw new TypeError('Invalid argument');
  779. }
  780. if (!('radius' in val && val.center))
  781. throw new Error('center and radius are required');
  782. var conds = this._conditions[path] || (this._conditions[path] = {});
  783. var type = val.spherical
  784. ? '$centerSphere'
  785. : '$center';
  786. var wKey = this._geoComparison || $withinCmd;
  787. conds[wKey] = {};
  788. conds[wKey][type] = [val.center, val.radius];
  789. if ('unique' in val)
  790. conds[wKey].$uniqueDocs = !!val.unique;
  791. return this;
  792. };
  793. /**
  794. * Specifies a `$near` or `$nearSphere` condition
  795. *
  796. * These operators return documents sorted by distance.
  797. *
  798. * ####Example
  799. *
  800. * query.where('loc').near({ center: [10, 10] });
  801. * query.where('loc').near({ center: [10, 10], maxDistance: 5 });
  802. * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
  803. * query.near('loc', { center: [10, 10], maxDistance: 5 });
  804. * query.near({ center: { type: 'Point', coordinates: [..] }})
  805. * query.near().geometry({ type: 'Point', coordinates: [..] })
  806. *
  807. * @param {String} [path]
  808. * @param {Object} val
  809. * @return {Query} this
  810. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  811. * @api public
  812. */
  813. Query.prototype.near = function near() {
  814. var path, val;
  815. this._geoComparison = '$near';
  816. if (0 === arguments.length) {
  817. return this;
  818. } else if (1 === arguments.length) {
  819. this._ensurePath('near');
  820. path = this._path;
  821. val = arguments[0];
  822. } else if (2 === arguments.length) {
  823. path = arguments[0];
  824. val = arguments[1];
  825. } else {
  826. throw new TypeError('Invalid argument');
  827. }
  828. if (!val.center) {
  829. throw new Error('center is required');
  830. }
  831. var conds = this._conditions[path] || (this._conditions[path] = {});
  832. var type = val.spherical
  833. ? '$nearSphere'
  834. : '$near';
  835. // center could be a GeoJSON object or an Array
  836. if (Array.isArray(val.center)) {
  837. conds[type] = val.center;
  838. var radius = 'maxDistance' in val
  839. ? val.maxDistance
  840. : null;
  841. if (null != radius) {
  842. conds.$maxDistance = radius;
  843. }
  844. if (null != val.minDistance) {
  845. conds.$minDistance = val.minDistance;
  846. }
  847. } else {
  848. // GeoJSON?
  849. if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) {
  850. throw new Error(util.format('Invalid GeoJSON specified for %s', type));
  851. }
  852. conds[type] = { $geometry : val.center };
  853. // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere
  854. if ('maxDistance' in val) {
  855. conds[type]['$maxDistance'] = val.maxDistance;
  856. }
  857. if ('minDistance' in val) {
  858. conds[type]['$minDistance'] = val.minDistance;
  859. }
  860. }
  861. return this;
  862. };
  863. /**
  864. * Declares an intersects query for `geometry()`.
  865. *
  866. * ####Example
  867. *
  868. * query.where('path').intersects().geometry({
  869. * type: 'LineString'
  870. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  871. * })
  872. *
  873. * query.where('path').intersects({
  874. * type: 'LineString'
  875. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  876. * })
  877. *
  878. * @param {Object} [arg]
  879. * @return {Query} this
  880. * @api public
  881. */
  882. Query.prototype.intersects = function intersects() {
  883. // opinionated, must be used after where
  884. this._ensurePath('intersects');
  885. this._geoComparison = '$geoIntersects';
  886. if (0 === arguments.length) {
  887. return this;
  888. }
  889. var area = arguments[0];
  890. if (null != area && area.type && area.coordinates)
  891. return this.geometry(area);
  892. throw new TypeError('Invalid argument');
  893. };
  894. /**
  895. * Specifies a `$geometry` condition
  896. *
  897. * ####Example
  898. *
  899. * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
  900. * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
  901. *
  902. * // or
  903. * var polyB = [[ 0, 0 ], [ 1, 1 ]]
  904. * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
  905. *
  906. * // or
  907. * var polyC = [ 0, 0 ]
  908. * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
  909. *
  910. * // or
  911. * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
  912. *
  913. * ####NOTE:
  914. *
  915. * `geometry()` **must** come after either `intersects()` or `within()`.
  916. *
  917. * The `object` argument must contain `type` and `coordinates` properties.
  918. * - type {String}
  919. * - coordinates {Array}
  920. *
  921. * The most recent path passed to `where()` is used.
  922. *
  923. * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
  924. * @return {Query} this
  925. * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
  926. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  927. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  928. * @api public
  929. */
  930. Query.prototype.geometry = function geometry() {
  931. if (!('$within' == this._geoComparison ||
  932. '$geoWithin' == this._geoComparison ||
  933. '$near' == this._geoComparison ||
  934. '$geoIntersects' == this._geoComparison)) {
  935. throw new Error('geometry() must come after `within()`, `intersects()`, or `near()');
  936. }
  937. var val, path;
  938. if (1 === arguments.length) {
  939. this._ensurePath('geometry');
  940. path = this._path;
  941. val = arguments[0];
  942. } else {
  943. throw new TypeError('Invalid argument');
  944. }
  945. if (!(val.type && Array.isArray(val.coordinates))) {
  946. throw new TypeError('Invalid argument');
  947. }
  948. var conds = this._conditions[path] || (this._conditions[path] = {});
  949. conds[this._geoComparison] = { $geometry: val };
  950. return this;
  951. };
  952. // end spatial
  953. /**
  954. * Specifies which document fields to include or exclude
  955. *
  956. * ####String syntax
  957. *
  958. * 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.
  959. *
  960. * ####Example
  961. *
  962. * // include a and b, exclude c
  963. * query.select('a b -c');
  964. *
  965. * // or you may use object notation, useful when
  966. * // you have keys already prefixed with a "-"
  967. * query.select({a: 1, b: 1, c: 0});
  968. *
  969. * ####Note
  970. *
  971. * Cannot be used with `distinct()`
  972. *
  973. * @param {Object|String} arg
  974. * @return {Query} this
  975. * @see SchemaType
  976. * @api public
  977. */
  978. Query.prototype.select = function select() {
  979. var arg = arguments[0];
  980. if (!arg) return this;
  981. if (arguments.length !== 1) {
  982. throw new Error('Invalid select: select only takes 1 argument');
  983. }
  984. this._validate('select');
  985. var fields = this._fields || (this._fields = {});
  986. var type = typeof arg;
  987. var i, len;
  988. if (('string' == type || utils.isArgumentsObject(arg)) &&
  989. 'number' == typeof arg.length || Array.isArray(arg)) {
  990. if ('string' == type)
  991. arg = arg.split(/\s+/);
  992. for (i = 0, len = arg.length; i < len; ++i) {
  993. var field = arg[i];
  994. if (!field) continue;
  995. var include = '-' == field[0] ? 0 : 1;
  996. if (include === 0) field = field.substring(1);
  997. fields[field] = include;
  998. }
  999. return this;
  1000. }
  1001. if (utils.isObject(arg)) {
  1002. var keys = utils.keys(arg);
  1003. for (i = 0; i < keys.length; ++i) {
  1004. fields[keys[i]] = arg[keys[i]];
  1005. }
  1006. return this;
  1007. }
  1008. throw new TypeError('Invalid select() argument. Must be string or object.');
  1009. };
  1010. /**
  1011. * Specifies a $slice condition for a `path`
  1012. *
  1013. * ####Example
  1014. *
  1015. * query.slice('comments', 5)
  1016. * query.slice('comments', -5)
  1017. * query.slice('comments', [10, 5])
  1018. * query.where('comments').slice(5)
  1019. * query.where('comments').slice([-10, 5])
  1020. *
  1021. * @param {String} [path]
  1022. * @param {Number} val number/range of elements to slice
  1023. * @return {Query} this
  1024. * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
  1025. * @api public
  1026. */
  1027. Query.prototype.slice = function() {
  1028. if (0 === arguments.length)
  1029. return this;
  1030. this._validate('slice');
  1031. var path, val;
  1032. if (1 === arguments.length) {
  1033. var arg = arguments[0];
  1034. if (typeof arg === 'object' && !Array.isArray(arg)) {
  1035. var keys = Object.keys(arg);
  1036. var numKeys = keys.length;
  1037. for (var i = 0; i < numKeys; ++i) {
  1038. this.slice(keys[i], arg[keys[i]]);
  1039. }
  1040. return this;
  1041. }
  1042. this._ensurePath('slice');
  1043. path = this._path;
  1044. val = arguments[0];
  1045. } else if (2 === arguments.length) {
  1046. if ('number' === typeof arguments[0]) {
  1047. this._ensurePath('slice');
  1048. path = this._path;
  1049. val = slice(arguments);
  1050. } else {
  1051. path = arguments[0];
  1052. val = arguments[1];
  1053. }
  1054. } else if (3 === arguments.length) {
  1055. path = arguments[0];
  1056. val = slice(arguments, 1);
  1057. }
  1058. var myFields = this._fields || (this._fields = {});
  1059. myFields[path] = { '$slice': val };
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets the sort order
  1064. *
  1065. * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.
  1066. *
  1067. * 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.
  1068. *
  1069. * ####Example
  1070. *
  1071. * // these are equivalent
  1072. * query.sort({ field: 'asc', test: -1 });
  1073. * query.sort('field -test');
  1074. * query.sort([['field', 1], ['test', -1]]);
  1075. *
  1076. * ####Note
  1077. *
  1078. * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15).
  1079. * - Cannot be used with `distinct()`
  1080. *
  1081. * @param {Object|String|Array} arg
  1082. * @return {Query} this
  1083. * @api public
  1084. */
  1085. Query.prototype.sort = function(arg) {
  1086. if (!arg) return this;
  1087. var i, len, field;
  1088. this._validate('sort');
  1089. var type = typeof arg;
  1090. // .sort([['field', 1], ['test', -1]])
  1091. if (Array.isArray(arg)) {
  1092. len = arg.length;
  1093. for (i = 0; i < arg.length; ++i) {
  1094. if (!Array.isArray(arg[i])) {
  1095. throw new Error('Invalid sort() argument, must be array of arrays');
  1096. }
  1097. _pushArr(this.options, arg[i][0], arg[i][1]);
  1098. }
  1099. return this;
  1100. }
  1101. // .sort('field -test')
  1102. if (1 === arguments.length && 'string' == type) {
  1103. arg = arg.split(/\s+/);
  1104. len = arg.length;
  1105. for (i = 0; i < len; ++i) {
  1106. field = arg[i];
  1107. if (!field) continue;
  1108. var ascend = '-' == field[0] ? -1 : 1;
  1109. if (ascend === -1) field = field.substring(1);
  1110. push(this.options, field, ascend);
  1111. }
  1112. return this;
  1113. }
  1114. // .sort({ field: 1, test: -1 })
  1115. if (utils.isObject(arg)) {
  1116. var keys = utils.keys(arg);
  1117. for (i = 0; i < keys.length; ++i) {
  1118. field = keys[i];
  1119. push(this.options, field, arg[field]);
  1120. }
  1121. return this;
  1122. }
  1123. if (typeof Map !== 'undefined' && arg instanceof Map) {
  1124. _pushMap(this.options, arg);
  1125. return this;
  1126. }
  1127. throw new TypeError('Invalid sort() argument. Must be a string, object, or array.');
  1128. };
  1129. /*!
  1130. * @ignore
  1131. */
  1132. var _validSortValue = {
  1133. '1': 1,
  1134. '-1': -1,
  1135. 'asc': 1,
  1136. 'ascending': 1,
  1137. 'desc': -1,
  1138. 'descending': -1
  1139. };
  1140. function push(opts, field, value) {
  1141. if (Array.isArray(opts.sort)) {
  1142. throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' +
  1143. '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' +
  1144. '\n- `.sort({ field: 1, test: -1 })`');
  1145. }
  1146. var s;
  1147. if (value && value.$meta) {
  1148. s = opts.sort || (opts.sort = {});
  1149. s[field] = { $meta : value.$meta };
  1150. return;
  1151. }
  1152. s = opts.sort || (opts.sort = {});
  1153. var val = String(value || 1).toLowerCase();
  1154. val = _validSortValue[val];
  1155. if (!val) throw new TypeError('Invalid sort value: { ' + field + ': ' + value + ' }');
  1156. s[field] = val;
  1157. }
  1158. function _pushArr(opts, field, value) {
  1159. opts.sort = opts.sort || [];
  1160. if (!Array.isArray(opts.sort)) {
  1161. throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' +
  1162. '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' +
  1163. '\n- `.sort({ field: 1, test: -1 })`');
  1164. }
  1165. var val = String(value || 1).toLowerCase();
  1166. val = _validSortValue[val];
  1167. if (!val) throw new TypeError('Invalid sort value: [ ' + field + ', ' + value + ' ]');
  1168. opts.sort.push([field, val]);
  1169. }
  1170. function _pushMap(opts, map) {
  1171. opts.sort = opts.sort || new Map();
  1172. if (!(opts.sort instanceof Map)) {
  1173. throw new TypeError('Can\'t mix sort syntaxes. Use either array or ' +
  1174. 'object or map consistently');
  1175. }
  1176. map.forEach(function(value, key) {
  1177. var val = String(value || 1).toLowerCase();
  1178. val = _validSortValue[val];
  1179. if (!val) throw new TypeError('Invalid sort value: < ' + key + ': ' + value + ' >');
  1180. opts.sort.set(key, val);
  1181. });
  1182. }
  1183. /**
  1184. * Specifies the limit option.
  1185. *
  1186. * ####Example
  1187. *
  1188. * query.limit(20)
  1189. *
  1190. * ####Note
  1191. *
  1192. * Cannot be used with `distinct()`
  1193. *
  1194. * @method limit
  1195. * @memberOf Query
  1196. * @param {Number} val
  1197. * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D
  1198. * @api public
  1199. */
  1200. /**
  1201. * Specifies the skip option.
  1202. *
  1203. * ####Example
  1204. *
  1205. * query.skip(100).limit(20)
  1206. *
  1207. * ####Note
  1208. *
  1209. * Cannot be used with `distinct()`
  1210. *
  1211. * @method skip
  1212. * @memberOf Query
  1213. * @param {Number} val
  1214. * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D
  1215. * @api public
  1216. */
  1217. /**
  1218. * Specifies the maxScan option.
  1219. *
  1220. * ####Example
  1221. *
  1222. * query.maxScan(100)
  1223. *
  1224. * ####Note
  1225. *
  1226. * Cannot be used with `distinct()`
  1227. *
  1228. * @method maxScan
  1229. * @memberOf Query
  1230. * @param {Number} val
  1231. * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan
  1232. * @api public
  1233. */
  1234. /**
  1235. * Specifies the batchSize option.
  1236. *
  1237. * ####Example
  1238. *
  1239. * query.batchSize(100)
  1240. *
  1241. * ####Note
  1242. *
  1243. * Cannot be used with `distinct()`
  1244. *
  1245. * @method batchSize
  1246. * @memberOf Query
  1247. * @param {Number} val
  1248. * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D
  1249. * @api public
  1250. */
  1251. /**
  1252. * Specifies the `comment` option.
  1253. *
  1254. * ####Example
  1255. *
  1256. * query.comment('login query')
  1257. *
  1258. * ####Note
  1259. *
  1260. * Cannot be used with `distinct()`
  1261. *
  1262. * @method comment
  1263. * @memberOf Query
  1264. * @param {Number} val
  1265. * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment
  1266. * @api public
  1267. */
  1268. /*!
  1269. * limit, skip, maxScan, batchSize, comment
  1270. *
  1271. * Sets these associated options.
  1272. *
  1273. * query.comment('feed query');
  1274. */
  1275. ['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function(method) {
  1276. Query.prototype[method] = function(v) {
  1277. this._validate(method);
  1278. this.options[method] = v;
  1279. return this;
  1280. };
  1281. });
  1282. /**
  1283. * Specifies the maxTimeMS option.
  1284. *
  1285. * ####Example
  1286. *
  1287. * query.maxTime(100)
  1288. * query.maxTimeMS(100)
  1289. *
  1290. * @method maxTime
  1291. * @memberOf Query
  1292. * @param {Number} ms
  1293. * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS
  1294. * @api public
  1295. */
  1296. Query.prototype.maxTime = Query.prototype.maxTimeMS = function(ms) {
  1297. this._validate('maxTime');
  1298. this.options.maxTimeMS = ms;
  1299. return this;
  1300. };
  1301. /**
  1302. * Specifies this query as a `snapshot` query.
  1303. *
  1304. * ####Example
  1305. *
  1306. * mquery().snapshot() // true
  1307. * mquery().snapshot(true)
  1308. * mquery().snapshot(false)
  1309. *
  1310. * ####Note
  1311. *
  1312. * Cannot be used with `distinct()`
  1313. *
  1314. * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D
  1315. * @return {Query} this
  1316. * @api public
  1317. */
  1318. Query.prototype.snapshot = function() {
  1319. this._validate('snapshot');
  1320. this.options.snapshot = arguments.length
  1321. ? !!arguments[0]
  1322. : true;
  1323. return this;
  1324. };
  1325. /**
  1326. * Sets query hints.
  1327. *
  1328. * ####Example
  1329. *
  1330. * query.hint({ indexA: 1, indexB: -1});
  1331. * query.hint('indexA_1_indexB_1');
  1332. *
  1333. * ####Note
  1334. *
  1335. * Cannot be used with `distinct()`
  1336. *
  1337. * @param {Object|string} val a hint object or the index name
  1338. * @return {Query} this
  1339. * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint
  1340. * @api public
  1341. */
  1342. Query.prototype.hint = function() {
  1343. if (0 === arguments.length) return this;
  1344. this._validate('hint');
  1345. var arg = arguments[0];
  1346. if (utils.isObject(arg)) {
  1347. var hint = this.options.hint || (this.options.hint = {});
  1348. // must keep object keys in order so don't use Object.keys()
  1349. for (var k in arg) {
  1350. hint[k] = arg[k];
  1351. }
  1352. return this;
  1353. }
  1354. if (typeof arg === 'string') {
  1355. this.options.hint = arg;
  1356. return this;
  1357. }
  1358. throw new TypeError('Invalid hint. ' + arg);
  1359. };
  1360. /**
  1361. * Requests acknowledgement that this operation has been persisted to MongoDB's
  1362. * on-disk journal.
  1363. * This option is only valid for operations that write to the database:
  1364. *
  1365. * - `deleteOne()`
  1366. * - `deleteMany()`
  1367. * - `findOneAndDelete()`
  1368. * - `findOneAndUpdate()`
  1369. * - `remove()`
  1370. * - `update()`
  1371. * - `updateOne()`
  1372. * - `updateMany()`
  1373. *
  1374. * Defaults to the `j` value if it is specified in writeConcern options
  1375. *
  1376. * ####Example:
  1377. *
  1378. * mquery().w(2).j(true).wtimeout(2000);
  1379. *
  1380. * @method j
  1381. * @memberOf Query
  1382. * @instance
  1383. * @param {boolean} val
  1384. * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option
  1385. * @return {Query} this
  1386. * @api public
  1387. */
  1388. Query.prototype.j = function j(val) {
  1389. this.options.j = val;
  1390. return this;
  1391. };
  1392. /**
  1393. * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences.
  1394. *
  1395. * ####Example:
  1396. *
  1397. * query.slaveOk() // true
  1398. * query.slaveOk(true)
  1399. * query.slaveOk(false)
  1400. *
  1401. * @deprecated use read() preferences instead if on mongodb >= 2.2
  1402. * @param {Boolean} v defaults to true
  1403. * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
  1404. * @see read()
  1405. * @return {Query} this
  1406. * @api public
  1407. */
  1408. Query.prototype.slaveOk = function(v) {
  1409. this.options.slaveOk = arguments.length ? !!v : true;
  1410. return this;
  1411. };
  1412. /**
  1413. * Sets the readPreference option for the query.
  1414. *
  1415. * ####Example:
  1416. *
  1417. * new Query().read('primary')
  1418. * new Query().read('p') // same as primary
  1419. *
  1420. * new Query().read('primaryPreferred')
  1421. * new Query().read('pp') // same as primaryPreferred
  1422. *
  1423. * new Query().read('secondary')
  1424. * new Query().read('s') // same as secondary
  1425. *
  1426. * new Query().read('secondaryPreferred')
  1427. * new Query().read('sp') // same as secondaryPreferred
  1428. *
  1429. * new Query().read('nearest')
  1430. * new Query().read('n') // same as nearest
  1431. *
  1432. * // you can also use mongodb.ReadPreference class to also specify tags
  1433. * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]))
  1434. *
  1435. * new Query().setReadPreference('primary') // alias of .read()
  1436. *
  1437. * ####Preferences:
  1438. *
  1439. * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
  1440. * secondary Read from secondary if available, otherwise error.
  1441. * primaryPreferred Read from primary if available, otherwise a secondary.
  1442. * secondaryPreferred Read from a secondary if available, otherwise read from the primary.
  1443. * 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.
  1444. *
  1445. * Aliases
  1446. *
  1447. * p primary
  1448. * pp primaryPreferred
  1449. * s secondary
  1450. * sp secondaryPreferred
  1451. * n nearest
  1452. *
  1453. * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).
  1454. *
  1455. * @param {String|ReadPreference} pref one of the listed preference options or their aliases
  1456. * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
  1457. * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
  1458. * @return {Query} this
  1459. * @api public
  1460. */
  1461. Query.prototype.read = Query.prototype.setReadPreference = function(pref) {
  1462. if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) {
  1463. console.error('Deprecation warning: \'tags\' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead.');
  1464. Query.prototype.read.deprecationWarningIssued = true;
  1465. }
  1466. this.options.readPreference = utils.readPref(pref);
  1467. return this;
  1468. };
  1469. /**
  1470. * Sets the readConcern option for the query.
  1471. *
  1472. * ####Example:
  1473. *
  1474. * new Query().readConcern('local')
  1475. * new Query().readConcern('l') // same as local
  1476. *
  1477. * new Query().readConcern('available')
  1478. * new Query().readConcern('a') // same as available
  1479. *
  1480. * new Query().readConcern('majority')
  1481. * new Query().readConcern('m') // same as majority
  1482. *
  1483. * new Query().readConcern('linearizable')
  1484. * new Query().readConcern('lz') // same as linearizable
  1485. *
  1486. * new Query().readConcern('snapshot')
  1487. * new Query().readConcern('s') // same as snapshot
  1488. *
  1489. * new Query().r('s') // r is alias of readConcern
  1490. *
  1491. *
  1492. * ####Read Concern Level:
  1493. *
  1494. * local MongoDB 3.2+ 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).
  1495. * available MongoDB 3.6+ 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).
  1496. * majority MongoDB 3.2+ 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.
  1497. * linearizable MongoDB 3.4+ 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.
  1498. * snapshot MongoDB 4.0+ 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.
  1499. *
  1500. *
  1501. * Aliases
  1502. *
  1503. * l local
  1504. * a available
  1505. * m majority
  1506. * lz linearizable
  1507. * s snapshot
  1508. *
  1509. * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/).
  1510. *
  1511. * @param {String} level one of the listed read concern level or their aliases
  1512. * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/
  1513. * @return {Query} this
  1514. * @api public
  1515. */
  1516. Query.prototype.readConcern = Query.prototype.r = function(level) {
  1517. this.options.readConcern = utils.readConcern(level);
  1518. return this;
  1519. };
  1520. /**
  1521. * Sets tailable option.
  1522. *
  1523. * ####Example
  1524. *
  1525. * query.tailable() <== true
  1526. * query.tailable(true)
  1527. * query.tailable(false)
  1528. *
  1529. * ####Note
  1530. *
  1531. * Cannot be used with `distinct()`
  1532. *
  1533. * @param {Boolean} v defaults to true
  1534. * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors
  1535. * @api public
  1536. */
  1537. Query.prototype.tailable = function() {
  1538. this._validate('tailable');
  1539. this.options.tailable = arguments.length
  1540. ? !!arguments[0]
  1541. : true;
  1542. return this;
  1543. };
  1544. /**
  1545. * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
  1546. * that must acknowledge this write before this write is considered successful.
  1547. * This option is only valid for operations that write to the database:
  1548. *
  1549. * - `deleteOne()`
  1550. * - `deleteMany()`
  1551. * - `findOneAndDelete()`
  1552. * - `findOneAndUpdate()`
  1553. * - `remove()`
  1554. * - `update()`
  1555. * - `updateOne()`
  1556. * - `updateMany()`
  1557. *
  1558. * Defaults to the `w` value if it is specified in writeConcern options
  1559. *
  1560. * ####Example:
  1561. *
  1562. * mquery().writeConcern(0)
  1563. * mquery().writeConcern(1)
  1564. * mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 })
  1565. * mquery().writeConcern('majority')
  1566. * mquery().writeConcern('m') // same as majority
  1567. * mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead
  1568. * mquery().w(1) // w is alias of writeConcern
  1569. *
  1570. * @method writeConcern
  1571. * @memberOf Query
  1572. * @instance
  1573. * @param {String|number|object} concern 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option).
  1574. * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option
  1575. * @return {Query} this
  1576. * @api public
  1577. */
  1578. Query.prototype.writeConcern = Query.prototype.w = function writeConcern(concern) {
  1579. if ('object' === typeof concern) {
  1580. if ('undefined' !== typeof concern.j) this.options.j = concern.j;
  1581. if ('undefined' !== typeof concern.w) this.options.w = concern.w;
  1582. if ('undefined' !== typeof concern.wtimeout) this.options.wtimeout = concern.wtimeout;
  1583. } else {
  1584. this.options.w = 'm' === concern ? 'majority' : concern;
  1585. }
  1586. return this;
  1587. };
  1588. /**
  1589. * Specifies a time limit, in milliseconds, for the write concern.
  1590. * If `ms > 1`, it is maximum amount of time to wait for this write
  1591. * to propagate through the replica set before this operation fails.
  1592. * The default is `0`, which means no timeout.
  1593. *
  1594. * This option is only valid for operations that write to the database:
  1595. *
  1596. * - `deleteOne()`
  1597. * - `deleteMany()`
  1598. * - `findOneAndDelete()`
  1599. * - `findOneAndUpdate()`
  1600. * - `remove()`
  1601. * - `update()`
  1602. * - `updateOne()`
  1603. * - `updateMany()`
  1604. *
  1605. * Defaults to `wtimeout` value if it is specified in writeConcern
  1606. *
  1607. * ####Example:
  1608. *
  1609. * mquery().w(2).j(true).wtimeout(2000)
  1610. *
  1611. * @method wtimeout
  1612. * @memberOf Query
  1613. * @instance
  1614. * @param {number} ms number of milliseconds to wait
  1615. * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout
  1616. * @return {Query} this
  1617. * @api public
  1618. */
  1619. Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout(ms) {
  1620. this.options.wtimeout = ms;
  1621. return this;
  1622. };
  1623. /**
  1624. * Merges another Query or conditions object into this one.
  1625. *
  1626. * When a Query is passed, conditions, field selection and options are merged.
  1627. *
  1628. * @param {Query|Object} source
  1629. * @return {Query} this
  1630. */
  1631. Query.prototype.merge = function(source) {
  1632. if (!source)
  1633. return this;
  1634. if (!Query.canMerge(source))
  1635. throw new TypeError('Invalid argument. Expected instanceof mquery or plain object');
  1636. if (source instanceof Query) {
  1637. // if source has a feature, apply it to ourselves
  1638. if (source._conditions) {
  1639. utils.merge(this._conditions, source._conditions);
  1640. }
  1641. if (source._fields) {
  1642. this._fields || (this._fields = {});
  1643. utils.merge(this._fields, source._fields);
  1644. }
  1645. if (source.options) {
  1646. this.options || (this.options = {});
  1647. utils.merge(this.options, source.options);
  1648. }
  1649. if (source._update) {
  1650. this._update || (this._update = {});
  1651. utils.mergeClone(this._update, source._update);
  1652. }
  1653. if (source._distinct) {
  1654. this._distinct = source._distinct;
  1655. }
  1656. return this;
  1657. }
  1658. // plain object
  1659. utils.merge(this._conditions, source);
  1660. return this;
  1661. };
  1662. /**
  1663. * Finds documents.
  1664. *
  1665. * Passing a `callback` executes the query.
  1666. *
  1667. * ####Example
  1668. *
  1669. * query.find()
  1670. * query.find(callback)
  1671. * query.find({ name: 'Burning Lights' }, callback)
  1672. *
  1673. * @param {Object} [criteria] mongodb selector
  1674. * @param {Function} [callback]
  1675. * @return {Query} this
  1676. * @api public
  1677. */
  1678. Query.prototype.find = function(criteria, callback) {
  1679. this.op = 'find';
  1680. if ('function' === typeof criteria) {
  1681. callback = criteria;
  1682. criteria = undefined;
  1683. } else if (Query.canMerge(criteria)) {
  1684. this.merge(criteria);
  1685. }
  1686. if (!callback) return this;
  1687. var conds = this._conditions;
  1688. var options = this._optionsForExec();
  1689. if (this.$useProjection) {
  1690. options.projection = this._fieldsForExec();
  1691. } else {
  1692. options.fields = this._fieldsForExec();
  1693. }
  1694. debug('find', this._collection.collectionName, conds, options);
  1695. callback = this._wrapCallback('find', callback, {
  1696. conditions: conds,
  1697. options: options
  1698. });
  1699. this._collection.find(conds, options, utils.tick(callback));
  1700. return this;
  1701. };
  1702. /**
  1703. * Returns the query cursor
  1704. *
  1705. * ####Examples
  1706. *
  1707. * query.find().cursor();
  1708. * query.cursor({ name: 'Burning Lights' });
  1709. *
  1710. * @param {Object} [criteria] mongodb selector
  1711. * @return {Object} cursor
  1712. * @api public
  1713. */
  1714. Query.prototype.cursor = function cursor(criteria) {
  1715. if (this.op) {
  1716. if (this.op !== 'find') {
  1717. throw new TypeError('.cursor only support .find method');
  1718. }
  1719. } else {
  1720. this.find(criteria);
  1721. }
  1722. var conds = this._conditions;
  1723. var options = this._optionsForExec();
  1724. if (this.$useProjection) {
  1725. options.projection = this._fieldsForExec();
  1726. } else {
  1727. options.fields = this._fieldsForExec();
  1728. }
  1729. debug('findCursor', this._collection.collectionName, conds, options);
  1730. return this._collection.findCursor(conds, options);
  1731. };
  1732. /**
  1733. * Executes the query as a findOne() operation.
  1734. *
  1735. * Passing a `callback` executes the query.
  1736. *
  1737. * ####Example
  1738. *
  1739. * query.findOne().where('name', /^Burning/);
  1740. *
  1741. * query.findOne({ name: /^Burning/ })
  1742. *
  1743. * query.findOne({ name: /^Burning/ }, callback); // executes
  1744. *
  1745. * query.findOne(function (err, doc) {
  1746. * if (err) return handleError(err);
  1747. * if (doc) {
  1748. * // doc may be null if no document matched
  1749. *
  1750. * }
  1751. * });
  1752. *
  1753. * @param {Object|Query} [criteria] mongodb selector
  1754. * @param {Function} [callback]
  1755. * @return {Query} this
  1756. * @api public
  1757. */
  1758. Query.prototype.findOne = function(criteria, callback) {
  1759. this.op = 'findOne';
  1760. if ('function' === typeof criteria) {
  1761. callback = criteria;
  1762. criteria = undefined;
  1763. } else if (Query.canMerge(criteria)) {
  1764. this.merge(criteria);
  1765. }
  1766. if (!callback) return this;
  1767. var conds = this._conditions;
  1768. var options = this._optionsForExec();
  1769. if (this.$useProjection) {
  1770. options.projection = this._fieldsForExec();
  1771. } else {
  1772. options.fields = this._fieldsForExec();
  1773. }
  1774. debug('findOne', this._collection.collectionName, conds, options);
  1775. callback = this._wrapCallback('findOne', callback, {
  1776. conditions: conds,
  1777. options: options
  1778. });
  1779. this._collection.findOne(conds, options, utils.tick(callback));
  1780. return this;
  1781. };
  1782. /**
  1783. * Exectues the query as a count() operation.
  1784. *
  1785. * Passing a `callback` executes the query.
  1786. *
  1787. * ####Example
  1788. *
  1789. * query.count().where('color', 'black').exec(callback);
  1790. *
  1791. * query.count({ color: 'black' }).count(callback)
  1792. *
  1793. * query.count({ color: 'black' }, callback)
  1794. *
  1795. * query.where('color', 'black').count(function (err, count) {
  1796. * if (err) return handleError(err);
  1797. * console.log('there are %d kittens', count);
  1798. * })
  1799. *
  1800. * @param {Object} [criteria] mongodb selector
  1801. * @param {Function} [callback]
  1802. * @return {Query} this
  1803. * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count
  1804. * @api public
  1805. */
  1806. Query.prototype.count = function(criteria, callback) {
  1807. this.op = 'count';
  1808. this._validate();
  1809. if ('function' === typeof criteria) {
  1810. callback = criteria;
  1811. criteria = undefined;
  1812. } else if (Query.canMerge(criteria)) {
  1813. this.merge(criteria);
  1814. }
  1815. if (!callback) return this;
  1816. var conds = this._conditions,
  1817. options = this._optionsForExec();
  1818. debug('count', this._collection.collectionName, conds, options);
  1819. callback = this._wrapCallback('count', callback, {
  1820. conditions: conds,
  1821. options: options
  1822. });
  1823. this._collection.count(conds, options, utils.tick(callback));
  1824. return this;
  1825. };
  1826. /**
  1827. * Declares or executes a distinct() operation.
  1828. *
  1829. * Passing a `callback` executes the query.
  1830. *
  1831. * ####Example
  1832. *
  1833. * distinct(criteria, field, fn)
  1834. * distinct(criteria, field)
  1835. * distinct(field, fn)
  1836. * distinct(field)
  1837. * distinct(fn)
  1838. * distinct()
  1839. *
  1840. * @param {Object|Query} [criteria]
  1841. * @param {String} [field]
  1842. * @param {Function} [callback]
  1843. * @return {Query} this
  1844. * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct
  1845. * @api public
  1846. */
  1847. Query.prototype.distinct = function(criteria, field, callback) {
  1848. this.op = 'distinct';
  1849. this._validate();
  1850. if (!callback) {
  1851. switch (typeof field) {
  1852. case 'function':
  1853. callback = field;
  1854. if ('string' == typeof criteria) {
  1855. field = criteria;
  1856. criteria = undefined;
  1857. }
  1858. break;
  1859. case 'undefined':
  1860. case 'string':
  1861. break;
  1862. default:
  1863. throw new TypeError('Invalid `field` argument. Must be string or function');
  1864. }
  1865. switch (typeof criteria) {
  1866. case 'function':
  1867. callback = criteria;
  1868. criteria = field = undefined;
  1869. break;
  1870. case 'string':
  1871. field = criteria;
  1872. criteria = undefined;
  1873. break;
  1874. }
  1875. }
  1876. if ('string' == typeof field) {
  1877. this._distinct = field;
  1878. }
  1879. if (Query.canMerge(criteria)) {
  1880. this.merge(criteria);
  1881. }
  1882. if (!callback) {
  1883. return this;
  1884. }
  1885. if (!this._distinct) {
  1886. throw new Error('No value for `distinct` has been declared');
  1887. }
  1888. var conds = this._conditions,
  1889. options = this._optionsForExec();
  1890. debug('distinct', this._collection.collectionName, conds, options);
  1891. callback = this._wrapCallback('distinct', callback, {
  1892. conditions: conds,
  1893. options: options
  1894. });
  1895. this._collection.distinct(this._distinct, conds, options, utils.tick(callback));
  1896. return this;
  1897. };
  1898. /**
  1899. * Declare and/or execute this query as an update() operation. By default,
  1900. * `update()` only modifies the _first_ document that matches `criteria`.
  1901. *
  1902. * _All paths passed that are not $atomic operations will become $set ops._
  1903. *
  1904. * ####Example
  1905. *
  1906. * mquery({ _id: id }).update({ title: 'words' }, ...)
  1907. *
  1908. * becomes
  1909. *
  1910. * collection.update({ _id: id }, { $set: { title: 'words' }}, ...)
  1911. *
  1912. * ####Note
  1913. *
  1914. * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.
  1915. *
  1916. * ####Note
  1917. *
  1918. * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method.
  1919. *
  1920. * var q = mquery(collection).where({ _id: id });
  1921. * q.update({ $set: { name: 'bob' }}).update(); // not executed
  1922. *
  1923. * var q = mquery(collection).where({ _id: id });
  1924. * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe
  1925. *
  1926. * // keys that are not $atomic ops become $set.
  1927. * // this executes the same command as the previous example.
  1928. * q.update({ name: 'bob' }).where({ _id: id }).exec();
  1929. *
  1930. * var q = mquery(collection).update(); // not executed
  1931. *
  1932. * // overwriting with empty docs
  1933. * var q.where({ _id: id }).setOptions({ overwrite: true })
  1934. * q.update({ }, callback); // executes
  1935. *
  1936. * // multi update with overwrite to empty doc
  1937. * var q = mquery(collection).where({ _id: id });
  1938. * q.setOptions({ multi: true, overwrite: true })
  1939. * q.update({ });
  1940. * q.update(callback); // executed
  1941. *
  1942. * // multi updates
  1943. * mquery()
  1944. * .collection(coll)
  1945. * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
  1946. * // more multi updates
  1947. * mquery({ })
  1948. * .collection(coll)
  1949. * .setOptions({ multi: true })
  1950. * .update({ $set: { arr: [] }}, callback)
  1951. *
  1952. * // single update by default
  1953. * mquery({ email: 'address@example.com' })
  1954. * .collection(coll)
  1955. * .update({ $inc: { counter: 1 }}, callback)
  1956. *
  1957. * // summary
  1958. * update(criteria, doc, opts, cb) // executes
  1959. * update(criteria, doc, opts)
  1960. * update(criteria, doc, cb) // executes
  1961. * update(criteria, doc)
  1962. * update(doc, cb) // executes
  1963. * update(doc)
  1964. * update(cb) // executes
  1965. * update(true) // executes (unsafe write)
  1966. * update()
  1967. *
  1968. * @param {Object} [criteria]
  1969. * @param {Object} [doc] the update command
  1970. * @param {Object} [options]
  1971. * @param {Function} [callback]
  1972. * @return {Query} this
  1973. * @api public
  1974. */
  1975. Query.prototype.update = function update(criteria, doc, options, callback) {
  1976. var force;
  1977. switch (arguments.length) {
  1978. case 3:
  1979. if ('function' == typeof options) {
  1980. callback = options;
  1981. options = undefined;
  1982. }
  1983. break;
  1984. case 2:
  1985. if ('function' == typeof doc) {
  1986. callback = doc;
  1987. doc = criteria;
  1988. criteria = undefined;
  1989. }
  1990. break;
  1991. case 1:
  1992. switch (typeof criteria) {
  1993. case 'function':
  1994. callback = criteria;
  1995. criteria = options = doc = undefined;
  1996. break;
  1997. case 'boolean':
  1998. // execution with no callback (unsafe write)
  1999. force = criteria;
  2000. criteria = undefined;
  2001. break;
  2002. default:
  2003. doc = criteria;
  2004. criteria = options = undefined;
  2005. break;
  2006. }
  2007. }
  2008. return _update(this, 'update', criteria, doc, options, force, callback);
  2009. };
  2010. /**
  2011. * Declare and/or execute this query as an `updateMany()` operation. Identical
  2012. * to `update()` except `updateMany()` will update _all_ documents that match
  2013. * `criteria`, rather than just the first one.
  2014. *
  2015. * _All paths passed that are not $atomic operations will become $set ops._
  2016. *
  2017. * ####Example
  2018. *
  2019. * // Update every document whose `title` contains 'test'
  2020. * mquery().updateMany({ title: /test/ }, { year: 2017 })
  2021. *
  2022. * @param {Object} [criteria]
  2023. * @param {Object} [doc] the update command
  2024. * @param {Object} [options]
  2025. * @param {Function} [callback]
  2026. * @return {Query} this
  2027. * @api public
  2028. */
  2029. Query.prototype.updateMany = function updateMany(criteria, doc, options, callback) {
  2030. var force;
  2031. switch (arguments.length) {
  2032. case 3:
  2033. if ('function' == typeof options) {
  2034. callback = options;
  2035. options = undefined;
  2036. }
  2037. break;
  2038. case 2:
  2039. if ('function' == typeof doc) {
  2040. callback = doc;
  2041. doc = criteria;
  2042. criteria = undefined;
  2043. }
  2044. break;
  2045. case 1:
  2046. switch (typeof criteria) {
  2047. case 'function':
  2048. callback = criteria;
  2049. criteria = options = doc = undefined;
  2050. break;
  2051. case 'boolean':
  2052. // execution with no callback (unsafe write)
  2053. force = criteria;
  2054. criteria = undefined;
  2055. break;
  2056. default:
  2057. doc = criteria;
  2058. criteria = options = undefined;
  2059. break;
  2060. }
  2061. }
  2062. return _update(this, 'updateMany', criteria, doc, options, force, callback);
  2063. };
  2064. /**
  2065. * Declare and/or execute this query as an `updateOne()` operation. Identical
  2066. * to `update()` except `updateOne()` will _always_ update just one document,
  2067. * regardless of the `multi` option.
  2068. *
  2069. * _All paths passed that are not $atomic operations will become $set ops._
  2070. *
  2071. * ####Example
  2072. *
  2073. * // Update the first document whose `title` contains 'test'
  2074. * mquery().updateMany({ title: /test/ }, { year: 2017 })
  2075. *
  2076. * @param {Object} [criteria]
  2077. * @param {Object} [doc] the update command
  2078. * @param {Object} [options]
  2079. * @param {Function} [callback]
  2080. * @return {Query} this
  2081. * @api public
  2082. */
  2083. Query.prototype.updateOne = function updateOne(criteria, doc, options, callback) {
  2084. var force;
  2085. switch (arguments.length) {
  2086. case 3:
  2087. if ('function' == typeof options) {
  2088. callback = options;
  2089. options = undefined;
  2090. }
  2091. break;
  2092. case 2:
  2093. if ('function' == typeof doc) {
  2094. callback = doc;
  2095. doc = criteria;
  2096. criteria = undefined;
  2097. }
  2098. break;
  2099. case 1:
  2100. switch (typeof criteria) {
  2101. case 'function':
  2102. callback = criteria;
  2103. criteria = options = doc = undefined;
  2104. break;
  2105. case 'boolean':
  2106. // execution with no callback (unsafe write)
  2107. force = criteria;
  2108. criteria = undefined;
  2109. break;
  2110. default:
  2111. doc = criteria;
  2112. criteria = options = undefined;
  2113. break;
  2114. }
  2115. }
  2116. return _update(this, 'updateOne', criteria, doc, options, force, callback);
  2117. };
  2118. /**
  2119. * Declare and/or execute this query as an `replaceOne()` operation. Similar
  2120. * to `updateOne()`, except `replaceOne()` is not allowed to use atomic
  2121. * modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always
  2122. * replace the existing doc.
  2123. *
  2124. * ####Example
  2125. *
  2126. * // Replace the document with `_id` 1 with `{ _id: 1, year: 2017 }`
  2127. * mquery().replaceOne({ _id: 1 }, { year: 2017 })
  2128. *
  2129. * @param {Object} [criteria]
  2130. * @param {Object} [doc] the update command
  2131. * @param {Object} [options]
  2132. * @param {Function} [callback]
  2133. * @return {Query} this
  2134. * @api public
  2135. */
  2136. Query.prototype.replaceOne = function replaceOne(criteria, doc, options, callback) {
  2137. var force;
  2138. switch (arguments.length) {
  2139. case 3:
  2140. if ('function' == typeof options) {
  2141. callback = options;
  2142. options = undefined;
  2143. }
  2144. break;
  2145. case 2:
  2146. if ('function' == typeof doc) {
  2147. callback = doc;
  2148. doc = criteria;
  2149. criteria = undefined;
  2150. }
  2151. break;
  2152. case 1:
  2153. switch (typeof criteria) {
  2154. case 'function':
  2155. callback = criteria;
  2156. criteria = options = doc = undefined;
  2157. break;
  2158. case 'boolean':
  2159. // execution with no callback (unsafe write)
  2160. force = criteria;
  2161. criteria = undefined;
  2162. break;
  2163. default:
  2164. doc = criteria;
  2165. criteria = options = undefined;
  2166. break;
  2167. }
  2168. }
  2169. this.setOptions({ overwrite: true });
  2170. return _update(this, 'replaceOne', criteria, doc, options, force, callback);
  2171. };
  2172. /*!
  2173. * Internal helper for update, updateMany, updateOne
  2174. */
  2175. function _update(query, op, criteria, doc, options, force, callback) {
  2176. query.op = op;
  2177. if (Query.canMerge(criteria)) {
  2178. query.merge(criteria);
  2179. }
  2180. if (doc) {
  2181. query._mergeUpdate(doc);
  2182. }
  2183. if (utils.isObject(options)) {
  2184. // { overwrite: true }
  2185. query.setOptions(options);
  2186. }
  2187. // we are done if we don't have callback and they are
  2188. // not forcing an unsafe write.
  2189. if (!(force || callback)) {
  2190. return query;
  2191. }
  2192. if (!query._update ||
  2193. !query.options.overwrite && 0 === utils.keys(query._update).length) {
  2194. callback && utils.soon(callback.bind(null, null, 0));
  2195. return query;
  2196. }
  2197. options = query._optionsForExec();
  2198. if (!callback) options.safe = false;
  2199. criteria = query._conditions;
  2200. doc = query._updateForExec();
  2201. debug('update', query._collection.collectionName, criteria, doc, options);
  2202. callback = query._wrapCallback(op, callback, {
  2203. conditions: criteria,
  2204. doc: doc,
  2205. options: options
  2206. });
  2207. query._collection[op](criteria, doc, options, utils.tick(callback));
  2208. return query;
  2209. }
  2210. /**
  2211. * Declare and/or execute this query as a remove() operation.
  2212. *
  2213. * ####Example
  2214. *
  2215. * mquery(collection).remove({ artist: 'Anne Murray' }, callback)
  2216. *
  2217. * ####Note
  2218. *
  2219. * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method.
  2220. *
  2221. * // not executed
  2222. * var query = mquery(collection).remove({ name: 'Anne Murray' })
  2223. *
  2224. * // executed
  2225. * mquery(collection).remove({ name: 'Anne Murray' }, callback)
  2226. * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback)
  2227. *
  2228. * // executed without a callback (unsafe write)
  2229. * query.exec()
  2230. *
  2231. * // summary
  2232. * query.remove(conds, fn); // executes
  2233. * query.remove(conds)
  2234. * query.remove(fn) // executes
  2235. * query.remove()
  2236. *
  2237. * @param {Object|Query} [criteria] mongodb selector
  2238. * @param {Function} [callback]
  2239. * @return {Query} this
  2240. * @api public
  2241. */
  2242. Query.prototype.remove = function(criteria, callback) {
  2243. this.op = 'remove';
  2244. var force;
  2245. if ('function' === typeof criteria) {
  2246. callback = criteria;
  2247. criteria = undefined;
  2248. } else if (Query.canMerge(criteria)) {
  2249. this.merge(criteria);
  2250. } else if (true === criteria) {
  2251. force = criteria;
  2252. criteria = undefined;
  2253. }
  2254. if (!(force || callback))
  2255. return this;
  2256. var options = this._optionsForExec();
  2257. if (!callback) options.safe = false;
  2258. var conds = this._conditions;
  2259. debug('remove', this._collection.collectionName, conds, options);
  2260. callback = this._wrapCallback('remove', callback, {
  2261. conditions: conds,
  2262. options: options
  2263. });
  2264. this._collection.remove(conds, options, utils.tick(callback));
  2265. return this;
  2266. };
  2267. /**
  2268. * Declare and/or execute this query as a `deleteOne()` operation. Behaves like
  2269. * `remove()`, except for ignores the `justOne` option and always deletes at
  2270. * most one document.
  2271. *
  2272. * ####Example
  2273. *
  2274. * mquery(collection).deleteOne({ artist: 'Anne Murray' }, callback)
  2275. *
  2276. * @param {Object|Query} [criteria] mongodb selector
  2277. * @param {Function} [callback]
  2278. * @return {Query} this
  2279. * @api public
  2280. */
  2281. Query.prototype.deleteOne = function(criteria, callback) {
  2282. this.op = 'deleteOne';
  2283. var force;
  2284. if ('function' === typeof criteria) {
  2285. callback = criteria;
  2286. criteria = undefined;
  2287. } else if (Query.canMerge(criteria)) {
  2288. this.merge(criteria);
  2289. } else if (true === criteria) {
  2290. force = criteria;
  2291. criteria = undefined;
  2292. }
  2293. if (!(force || callback))
  2294. return this;
  2295. var options = this._optionsForExec();
  2296. if (!callback) options.safe = false;
  2297. delete options.justOne;
  2298. var conds = this._conditions;
  2299. debug('deleteOne', this._collection.collectionName, conds, options);
  2300. callback = this._wrapCallback('deleteOne', callback, {
  2301. conditions: conds,
  2302. options: options
  2303. });
  2304. this._collection.deleteOne(conds, options, utils.tick(callback));
  2305. return this;
  2306. };
  2307. /**
  2308. * Declare and/or execute this query as a `deleteMany()` operation. Behaves like
  2309. * `remove()`, except for ignores the `justOne` option and always deletes
  2310. * _every_ document that matches `criteria`.
  2311. *
  2312. * ####Example
  2313. *
  2314. * mquery(collection).deleteMany({ artist: 'Anne Murray' }, callback)
  2315. *
  2316. * @param {Object|Query} [criteria] mongodb selector
  2317. * @param {Function} [callback]
  2318. * @return {Query} this
  2319. * @api public
  2320. */
  2321. Query.prototype.deleteMany = function(criteria, callback) {
  2322. this.op = 'deleteMany';
  2323. var force;
  2324. if ('function' === typeof criteria) {
  2325. callback = criteria;
  2326. criteria = undefined;
  2327. } else if (Query.canMerge(criteria)) {
  2328. this.merge(criteria);
  2329. } else if (true === criteria) {
  2330. force = criteria;
  2331. criteria = undefined;
  2332. }
  2333. if (!(force || callback))
  2334. return this;
  2335. var options = this._optionsForExec();
  2336. if (!callback) options.safe = false;
  2337. delete options.justOne;
  2338. var conds = this._conditions;
  2339. debug('deleteOne', this._collection.collectionName, conds, options);
  2340. callback = this._wrapCallback('deleteOne', callback, {
  2341. conditions: conds,
  2342. options: options
  2343. });
  2344. this._collection.deleteMany(conds, options, utils.tick(callback));
  2345. return this;
  2346. };
  2347. /**
  2348. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
  2349. *
  2350. * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed.
  2351. *
  2352. * ####Available options
  2353. *
  2354. * - `new`: bool - true to return the modified document rather than the original. defaults to true
  2355. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  2356. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2357. *
  2358. * ####Examples
  2359. *
  2360. * query.findOneAndUpdate(conditions, update, options, callback) // executes
  2361. * query.findOneAndUpdate(conditions, update, options) // returns Query
  2362. * query.findOneAndUpdate(conditions, update, callback) // executes
  2363. * query.findOneAndUpdate(conditions, update) // returns Query
  2364. * query.findOneAndUpdate(update, callback) // returns Query
  2365. * query.findOneAndUpdate(update) // returns Query
  2366. * query.findOneAndUpdate(callback) // executes
  2367. * query.findOneAndUpdate() // returns Query
  2368. *
  2369. * @param {Object|Query} [query]
  2370. * @param {Object} [doc]
  2371. * @param {Object} [options]
  2372. * @param {Function} [callback]
  2373. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2374. * @return {Query} this
  2375. * @api public
  2376. */
  2377. Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
  2378. this.op = 'findOneAndUpdate';
  2379. this._validate();
  2380. switch (arguments.length) {
  2381. case 3:
  2382. if ('function' == typeof options) {
  2383. callback = options;
  2384. options = {};
  2385. }
  2386. break;
  2387. case 2:
  2388. if ('function' == typeof doc) {
  2389. callback = doc;
  2390. doc = criteria;
  2391. criteria = undefined;
  2392. }
  2393. options = undefined;
  2394. break;
  2395. case 1:
  2396. if ('function' == typeof criteria) {
  2397. callback = criteria;
  2398. criteria = options = doc = undefined;
  2399. } else {
  2400. doc = criteria;
  2401. criteria = options = undefined;
  2402. }
  2403. }
  2404. if (Query.canMerge(criteria)) {
  2405. this.merge(criteria);
  2406. }
  2407. // apply doc
  2408. if (doc) {
  2409. this._mergeUpdate(doc);
  2410. }
  2411. options && this.setOptions(options);
  2412. if (!callback) return this;
  2413. return this._findAndModify('update', callback);
  2414. };
  2415. /**
  2416. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
  2417. *
  2418. * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed.
  2419. *
  2420. * ####Available options
  2421. *
  2422. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2423. *
  2424. * ####Examples
  2425. *
  2426. * A.where().findOneAndRemove(conditions, options, callback) // executes
  2427. * A.where().findOneAndRemove(conditions, options) // return Query
  2428. * A.where().findOneAndRemove(conditions, callback) // executes
  2429. * A.where().findOneAndRemove(conditions) // returns Query
  2430. * A.where().findOneAndRemove(callback) // executes
  2431. * A.where().findOneAndRemove() // returns Query
  2432. * A.where().findOneAndDelete() // alias of .findOneAndRemove()
  2433. *
  2434. * @param {Object} [conditions]
  2435. * @param {Object} [options]
  2436. * @param {Function} [callback]
  2437. * @return {Query} this
  2438. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2439. * @api public
  2440. */
  2441. Query.prototype.findOneAndRemove = Query.prototype.findOneAndDelete = function(conditions, options, callback) {
  2442. this.op = 'findOneAndRemove';
  2443. this._validate();
  2444. if ('function' == typeof options) {
  2445. callback = options;
  2446. options = undefined;
  2447. } else if ('function' == typeof conditions) {
  2448. callback = conditions;
  2449. conditions = undefined;
  2450. }
  2451. // apply conditions
  2452. if (Query.canMerge(conditions)) {
  2453. this.merge(conditions);
  2454. }
  2455. // apply options
  2456. options && this.setOptions(options);
  2457. if (!callback) return this;
  2458. return this._findAndModify('remove', callback);
  2459. };
  2460. /**
  2461. * _findAndModify
  2462. *
  2463. * @param {String} type - either "remove" or "update"
  2464. * @param {Function} callback
  2465. * @api private
  2466. */
  2467. Query.prototype._findAndModify = function(type, callback) {
  2468. assert.equal('function', typeof callback);
  2469. var options = this._optionsForExec();
  2470. var fields;
  2471. var doc;
  2472. if ('remove' == type) {
  2473. options.remove = true;
  2474. } else {
  2475. if (!('new' in options)) options.new = true;
  2476. if (!('upsert' in options)) options.upsert = false;
  2477. doc = this._updateForExec();
  2478. if (!doc) {
  2479. if (options.upsert) {
  2480. // still need to do the upsert to empty doc
  2481. doc = { $set: {} };
  2482. } else {
  2483. return this.findOne(callback);
  2484. }
  2485. }
  2486. }
  2487. fields = this._fieldsForExec();
  2488. if (fields != null) {
  2489. if (this.$useProjection) {
  2490. options.projection = this._fieldsForExec();
  2491. } else {
  2492. options.fields = this._fieldsForExec();
  2493. }
  2494. }
  2495. var conds = this._conditions;
  2496. debug('findAndModify', this._collection.collectionName, conds, doc, options);
  2497. callback = this._wrapCallback('findAndModify', callback, {
  2498. conditions: conds,
  2499. doc: doc,
  2500. options: options
  2501. });
  2502. this._collection.findAndModify(conds, doc, options, utils.tick(callback));
  2503. return this;
  2504. };
  2505. /**
  2506. * Wrap callback to add tracing
  2507. *
  2508. * @param {Function} callback
  2509. * @param {Object} [queryInfo]
  2510. * @api private
  2511. */
  2512. Query.prototype._wrapCallback = function(method, callback, queryInfo) {
  2513. var traceFunction = this._traceFunction || Query.traceFunction;
  2514. if (traceFunction) {
  2515. queryInfo.collectionName = this._collection.collectionName;
  2516. var traceCallback = traceFunction &&
  2517. traceFunction.call(null, method, queryInfo, this);
  2518. var startTime = new Date().getTime();
  2519. return function wrapperCallback(err, result) {
  2520. if (traceCallback) {
  2521. var millis = new Date().getTime() - startTime;
  2522. traceCallback.call(null, err, result, millis);
  2523. }
  2524. if (callback) {
  2525. callback.apply(null, arguments);
  2526. }
  2527. };
  2528. }
  2529. return callback;
  2530. };
  2531. /**
  2532. * Add trace function that gets called when the query is executed.
  2533. * The function will be called with (method, queryInfo, query) and
  2534. * should return a callback function which will be called
  2535. * with (err, result, millis) when the query is complete.
  2536. *
  2537. * queryInfo is an object containing: {
  2538. * collectionName: <name of the collection>,
  2539. * conditions: <query criteria>,
  2540. * options: <comment, fields, readPreference, etc>,
  2541. * doc: [document to update, if applicable]
  2542. * }
  2543. *
  2544. * NOTE: Does not trace stream queries.
  2545. *
  2546. * @param {Function} traceFunction
  2547. * @return {Query} this
  2548. * @api public
  2549. */
  2550. Query.prototype.setTraceFunction = function(traceFunction) {
  2551. this._traceFunction = traceFunction;
  2552. return this;
  2553. };
  2554. /**
  2555. * Executes the query
  2556. *
  2557. * ####Examples
  2558. *
  2559. * query.exec();
  2560. * query.exec(callback);
  2561. * query.exec('update');
  2562. * query.exec('find', callback);
  2563. *
  2564. * @param {String|Function} [operation]
  2565. * @param {Function} [callback]
  2566. * @api public
  2567. */
  2568. Query.prototype.exec = function exec(op, callback) {
  2569. switch (typeof op) {
  2570. case 'function':
  2571. callback = op;
  2572. op = null;
  2573. break;
  2574. case 'string':
  2575. this.op = op;
  2576. break;
  2577. }
  2578. assert.ok(this.op, 'Missing query type: (find, update, etc)');
  2579. if ('update' == this.op || 'remove' == this.op) {
  2580. callback || (callback = true);
  2581. }
  2582. var _this = this;
  2583. if ('function' == typeof callback) {
  2584. this[this.op](callback);
  2585. } else {
  2586. return new Query.Promise(function(success, error) {
  2587. _this[_this.op](function(err, val) {
  2588. if (err) error(err);
  2589. else success(val);
  2590. success = error = null;
  2591. });
  2592. });
  2593. }
  2594. };
  2595. /**
  2596. * Returns a thunk which when called runs this.exec()
  2597. *
  2598. * The thunk receives a callback function which will be
  2599. * passed to `this.exec()`
  2600. *
  2601. * @return {Function}
  2602. * @api public
  2603. */
  2604. Query.prototype.thunk = function() {
  2605. var _this = this;
  2606. return function(cb) {
  2607. _this.exec(cb);
  2608. };
  2609. };
  2610. /**
  2611. * Executes the query returning a `Promise` which will be
  2612. * resolved with either the doc(s) or rejected with the error.
  2613. *
  2614. * @param {Function} [resolve]
  2615. * @param {Function} [reject]
  2616. * @return {Promise}
  2617. * @api public
  2618. */
  2619. Query.prototype.then = function(resolve, reject) {
  2620. var _this = this;
  2621. var promise = new Query.Promise(function(success, error) {
  2622. _this.exec(function(err, val) {
  2623. if (err) error(err);
  2624. else success(val);
  2625. success = error = null;
  2626. });
  2627. });
  2628. return promise.then(resolve, reject);
  2629. };
  2630. /**
  2631. * Returns a stream for the given find query.
  2632. *
  2633. * @throws Error if operation is not a find
  2634. * @returns {Stream} Node 0.8 style
  2635. */
  2636. Query.prototype.stream = function(streamOptions) {
  2637. if ('find' != this.op)
  2638. throw new Error('stream() is only available for find');
  2639. var conds = this._conditions;
  2640. var options = this._optionsForExec();
  2641. if (this.$useProjection) {
  2642. options.projection = this._fieldsForExec();
  2643. } else {
  2644. options.fields = this._fieldsForExec();
  2645. }
  2646. debug('stream', this._collection.collectionName, conds, options, streamOptions);
  2647. return this._collection.findStream(conds, options, streamOptions);
  2648. };
  2649. /**
  2650. * Determines if field selection has been made.
  2651. *
  2652. * @return {Boolean}
  2653. * @api public
  2654. */
  2655. Query.prototype.selected = function selected() {
  2656. return !!(this._fields && Object.keys(this._fields).length > 0);
  2657. };
  2658. /**
  2659. * Determines if inclusive field selection has been made.
  2660. *
  2661. * query.selectedInclusively() // false
  2662. * query.select('name')
  2663. * query.selectedInclusively() // true
  2664. * query.selectedExlusively() // false
  2665. *
  2666. * @returns {Boolean}
  2667. */
  2668. Query.prototype.selectedInclusively = function selectedInclusively() {
  2669. if (!this._fields) return false;
  2670. var keys = Object.keys(this._fields);
  2671. if (0 === keys.length) return false;
  2672. for (var i = 0; i < keys.length; ++i) {
  2673. var key = keys[i];
  2674. if (0 === this._fields[key]) return false;
  2675. if (this._fields[key] &&
  2676. typeof this._fields[key] === 'object' &&
  2677. this._fields[key].$meta) {
  2678. return false;
  2679. }
  2680. }
  2681. return true;
  2682. };
  2683. /**
  2684. * Determines if exclusive field selection has been made.
  2685. *
  2686. * query.selectedExlusively() // false
  2687. * query.select('-name')
  2688. * query.selectedExlusively() // true
  2689. * query.selectedInclusively() // false
  2690. *
  2691. * @returns {Boolean}
  2692. */
  2693. Query.prototype.selectedExclusively = function selectedExclusively() {
  2694. if (!this._fields) return false;
  2695. var keys = Object.keys(this._fields);
  2696. if (0 === keys.length) return false;
  2697. for (var i = 0; i < keys.length; ++i) {
  2698. var key = keys[i];
  2699. if (0 === this._fields[key]) return true;
  2700. }
  2701. return false;
  2702. };
  2703. /**
  2704. * Merges `doc` with the current update object.
  2705. *
  2706. * @param {Object} doc
  2707. */
  2708. Query.prototype._mergeUpdate = function(doc) {
  2709. if (!this._update) this._update = {};
  2710. if (doc instanceof Query) {
  2711. if (doc._update) {
  2712. utils.mergeClone(this._update, doc._update);
  2713. }
  2714. } else {
  2715. utils.mergeClone(this._update, doc);
  2716. }
  2717. };
  2718. /**
  2719. * Returns default options.
  2720. *
  2721. * @return {Object}
  2722. * @api private
  2723. */
  2724. Query.prototype._optionsForExec = function() {
  2725. var options = utils.clone(this.options);
  2726. return options;
  2727. };
  2728. /**
  2729. * Returns fields selection for this query.
  2730. *
  2731. * @return {Object}
  2732. * @api private
  2733. */
  2734. Query.prototype._fieldsForExec = function() {
  2735. return utils.clone(this._fields);
  2736. };
  2737. /**
  2738. * Return an update document with corrected $set operations.
  2739. *
  2740. * @api private
  2741. */
  2742. Query.prototype._updateForExec = function() {
  2743. var update = utils.clone(this._update),
  2744. ops = utils.keys(update),
  2745. i = ops.length,
  2746. ret = {};
  2747. while (i--) {
  2748. var op = ops[i];
  2749. if (this.options.overwrite) {
  2750. ret[op] = update[op];
  2751. continue;
  2752. }
  2753. if ('$' !== op[0]) {
  2754. // fix up $set sugar
  2755. if (!ret.$set) {
  2756. if (update.$set) {
  2757. ret.$set = update.$set;
  2758. } else {
  2759. ret.$set = {};
  2760. }
  2761. }
  2762. ret.$set[op] = update[op];
  2763. ops.splice(i, 1);
  2764. if (!~ops.indexOf('$set')) ops.push('$set');
  2765. } else if ('$set' === op) {
  2766. if (!ret.$set) {
  2767. ret[op] = update[op];
  2768. }
  2769. } else {
  2770. ret[op] = update[op];
  2771. }
  2772. }
  2773. this._compiledUpdate = ret;
  2774. return ret;
  2775. };
  2776. /**
  2777. * Make sure _path is set.
  2778. *
  2779. * @parmam {String} method
  2780. */
  2781. Query.prototype._ensurePath = function(method) {
  2782. if (!this._path) {
  2783. var msg = method + '() must be used after where() '
  2784. + 'when called with these arguments';
  2785. throw new Error(msg);
  2786. }
  2787. };
  2788. /*!
  2789. * Permissions
  2790. */
  2791. Query.permissions = require('./permissions');
  2792. Query._isPermitted = function(a, b) {
  2793. var denied = Query.permissions[b];
  2794. if (!denied) return true;
  2795. return true !== denied[a];
  2796. };
  2797. Query.prototype._validate = function(action) {
  2798. var fail;
  2799. var validator;
  2800. if (undefined === action) {
  2801. validator = Query.permissions[this.op];
  2802. if ('function' != typeof validator) return true;
  2803. fail = validator(this);
  2804. } else if (!Query._isPermitted(action, this.op)) {
  2805. fail = action;
  2806. }
  2807. if (fail) {
  2808. throw new Error(fail + ' cannot be used with ' + this.op);
  2809. }
  2810. };
  2811. /**
  2812. * Determines if `conds` can be merged using `mquery().merge()`
  2813. *
  2814. * @param {Object} conds
  2815. * @return {Boolean}
  2816. */
  2817. Query.canMerge = function(conds) {
  2818. return conds instanceof Query || utils.isObject(conds);
  2819. };
  2820. /**
  2821. * Set a trace function that will get called whenever a
  2822. * query is executed.
  2823. *
  2824. * See `setTraceFunction()` for details.
  2825. *
  2826. * @param {Object} conds
  2827. * @return {Boolean}
  2828. */
  2829. Query.setGlobalTraceFunction = function(traceFunction) {
  2830. Query.traceFunction = traceFunction;
  2831. };
  2832. /*!
  2833. * Exports.
  2834. */
  2835. Query.utils = utils;
  2836. Query.env = require('./env');
  2837. Query.Collection = require('./collection');
  2838. Query.BaseCollection = require('./collection/collection');
  2839. Query.Promise = require('bluebird');
  2840. module.exports = exports = Query;
  2841. // TODO
  2842. // test utils