Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query.js 136KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const CastError = require('./error/cast');
  6. const Kareem = require('kareem');
  7. const ObjectParameterError = require('./error/objectParameter');
  8. const QueryCursor = require('./cursor/QueryCursor');
  9. const ReadPreference = require('./driver').get().ReadPreference;
  10. const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
  11. const cast = require('./cast');
  12. const castUpdate = require('./helpers/query/castUpdate');
  13. const completeMany = require('./helpers/query/completeMany');
  14. const get = require('./helpers/get');
  15. const hasDollarKeys = require('./helpers/query/hasDollarKeys');
  16. const helpers = require('./queryhelpers');
  17. const isInclusive = require('./helpers/projection/isInclusive');
  18. const mquery = require('mquery');
  19. const selectPopulatedFields = require('./helpers/query/selectPopulatedFields');
  20. const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert');
  21. const slice = require('sliced');
  22. const updateValidators = require('./helpers/updateValidators');
  23. const util = require('util');
  24. const utils = require('./utils');
  25. const wrapThunk = require('./helpers/query/wrapThunk');
  26. /**
  27. * Query constructor used for building queries. You do not need
  28. * to instantiate a `Query` directly. Instead use Model functions like
  29. * [`Model.find()`](/docs/api.html#find_find).
  30. *
  31. * ####Example:
  32. *
  33. * const query = MyModel.find(); // `query` is an instance of `Query`
  34. * query.setOptions({ lean : true });
  35. * query.collection(MyModel.collection);
  36. * query.where('age').gte(21).exec(callback);
  37. *
  38. * // You can instantiate a query directly. There is no need to do
  39. * // this unless you're an advanced user with a very good reason to.
  40. * const query = new mongoose.Query();
  41. *
  42. * @param {Object} [options]
  43. * @param {Object} [model]
  44. * @param {Object} [conditions]
  45. * @param {Object} [collection] Mongoose collection
  46. * @api public
  47. */
  48. function Query(conditions, options, model, collection) {
  49. // this stuff is for dealing with custom queries created by #toConstructor
  50. if (!this._mongooseOptions) {
  51. this._mongooseOptions = {};
  52. }
  53. options = options || {};
  54. this._transforms = [];
  55. this._hooks = new Kareem();
  56. this._executionCount = 0;
  57. // this is the case where we have a CustomQuery, we need to check if we got
  58. // options passed in, and if we did, merge them in
  59. const keys = Object.keys(options);
  60. for (let i = 0; i < keys.length; ++i) {
  61. const k = keys[i];
  62. this._mongooseOptions[k] = options[k];
  63. }
  64. if (collection) {
  65. this.mongooseCollection = collection;
  66. }
  67. if (model) {
  68. this.model = model;
  69. this.schema = model.schema;
  70. }
  71. // this is needed because map reduce returns a model that can be queried, but
  72. // all of the queries on said model should be lean
  73. if (this.model && this.model._mapreduce) {
  74. this.lean();
  75. }
  76. // inherit mquery
  77. mquery.call(this, this.mongooseCollection, options);
  78. if (conditions) {
  79. this.find(conditions);
  80. }
  81. this.options = this.options || {};
  82. // For gh-6880. mquery still needs to support `fields` by default for old
  83. // versions of MongoDB
  84. this.$useProjection = true;
  85. const collation = get(this, 'schema.options.collation', null);
  86. if (collation != null) {
  87. this.options.collation = collation;
  88. }
  89. }
  90. /*!
  91. * inherit mquery
  92. */
  93. Query.prototype = new mquery;
  94. Query.prototype.constructor = Query;
  95. Query.base = mquery.prototype;
  96. /**
  97. * Flag to opt out of using `$geoWithin`.
  98. *
  99. * mongoose.Query.use$geoWithin = false;
  100. *
  101. * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work.
  102. *
  103. * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/
  104. * @default true
  105. * @property use$geoWithin
  106. * @memberOf Query
  107. * @receiver Query
  108. * @api public
  109. */
  110. Query.use$geoWithin = mquery.use$geoWithin;
  111. /**
  112. * Converts this query to a customized, reusable query constructor with all arguments and options retained.
  113. *
  114. * ####Example
  115. *
  116. * // Create a query for adventure movies and read from the primary
  117. * // node in the replica-set unless it is down, in which case we'll
  118. * // read from a secondary node.
  119. * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
  120. *
  121. * // create a custom Query constructor based off these settings
  122. * var Adventure = query.toConstructor();
  123. *
  124. * // Adventure is now a subclass of mongoose.Query and works the same way but with the
  125. * // default query parameters and options set.
  126. * Adventure().exec(callback)
  127. *
  128. * // further narrow down our query results while still using the previous settings
  129. * Adventure().where({ name: /^Life/ }).exec(callback);
  130. *
  131. * // since Adventure is a stand-alone constructor we can also add our own
  132. * // helper methods and getters without impacting global queries
  133. * Adventure.prototype.startsWith = function (prefix) {
  134. * this.where({ name: new RegExp('^' + prefix) })
  135. * return this;
  136. * }
  137. * Object.defineProperty(Adventure.prototype, 'highlyRated', {
  138. * get: function () {
  139. * this.where({ rating: { $gt: 4.5 }});
  140. * return this;
  141. * }
  142. * })
  143. * Adventure().highlyRated.startsWith('Life').exec(callback)
  144. *
  145. * New in 3.7.3
  146. *
  147. * @return {Query} subclass-of-Query
  148. * @api public
  149. */
  150. Query.prototype.toConstructor = function toConstructor() {
  151. const model = this.model;
  152. const coll = this.mongooseCollection;
  153. const CustomQuery = function(criteria, options) {
  154. if (!(this instanceof CustomQuery)) {
  155. return new CustomQuery(criteria, options);
  156. }
  157. this._mongooseOptions = utils.clone(p._mongooseOptions);
  158. Query.call(this, criteria, options || null, model, coll);
  159. };
  160. util.inherits(CustomQuery, model.Query);
  161. // set inherited defaults
  162. const p = CustomQuery.prototype;
  163. p.options = {};
  164. p.setOptions(this.options);
  165. p.op = this.op;
  166. p._conditions = utils.clone(this._conditions);
  167. p._fields = utils.clone(this._fields);
  168. p._update = utils.clone(this._update, {
  169. flattenDecimals: false
  170. });
  171. p._path = this._path;
  172. p._distinct = this._distinct;
  173. p._collection = this._collection;
  174. p._mongooseOptions = this._mongooseOptions;
  175. return CustomQuery;
  176. };
  177. /**
  178. * Specifies a javascript function or expression to pass to MongoDBs query system.
  179. *
  180. * ####Example
  181. *
  182. * query.$where('this.comments.length === 10 || this.name.length === 5')
  183. *
  184. * // or
  185. *
  186. * query.$where(function () {
  187. * return this.comments.length === 10 || this.name.length === 5;
  188. * })
  189. *
  190. * ####NOTE:
  191. *
  192. * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`.
  193. * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.**
  194. *
  195. * @see $where http://docs.mongodb.org/manual/reference/operator/where/
  196. * @method $where
  197. * @param {String|Function} js javascript string or function
  198. * @return {Query} this
  199. * @memberOf Query
  200. * @instance
  201. * @method $where
  202. * @api public
  203. */
  204. /**
  205. * Specifies a `path` for use with chaining.
  206. *
  207. * ####Example
  208. *
  209. * // instead of writing:
  210. * User.find({age: {$gte: 21, $lte: 65}}, callback);
  211. *
  212. * // we can instead write:
  213. * User.where('age').gte(21).lte(65);
  214. *
  215. * // passing query conditions is permitted
  216. * User.find().where({ name: 'vonderful' })
  217. *
  218. * // chaining
  219. * User
  220. * .where('age').gte(21).lte(65)
  221. * .where('name', /^vonderful/i)
  222. * .where('friends').slice(10)
  223. * .exec(callback)
  224. *
  225. * @method where
  226. * @memberOf Query
  227. * @instance
  228. * @param {String|Object} [path]
  229. * @param {any} [val]
  230. * @return {Query} this
  231. * @api public
  232. */
  233. Query.prototype.slice = function() {
  234. if (arguments.length === 0) {
  235. return this;
  236. }
  237. this._validate('slice');
  238. let path;
  239. let val;
  240. if (arguments.length === 1) {
  241. const arg = arguments[0];
  242. if (typeof arg === 'object' && !Array.isArray(arg)) {
  243. const keys = Object.keys(arg);
  244. const numKeys = keys.length;
  245. for (let i = 0; i < numKeys; ++i) {
  246. this.slice(keys[i], arg[keys[i]]);
  247. }
  248. return this;
  249. }
  250. this._ensurePath('slice');
  251. path = this._path;
  252. val = arguments[0];
  253. } else if (arguments.length === 2) {
  254. if ('number' === typeof arguments[0]) {
  255. this._ensurePath('slice');
  256. path = this._path;
  257. val = slice(arguments);
  258. } else {
  259. path = arguments[0];
  260. val = arguments[1];
  261. }
  262. } else if (arguments.length === 3) {
  263. path = arguments[0];
  264. val = slice(arguments, 1);
  265. }
  266. const p = {};
  267. p[path] = { $slice: val };
  268. this.select(p);
  269. return this;
  270. };
  271. /**
  272. * Specifies the complementary comparison value for paths specified with `where()`
  273. *
  274. * ####Example
  275. *
  276. * User.where('age').equals(49);
  277. *
  278. * // is the same as
  279. *
  280. * User.where('age', 49);
  281. *
  282. * @method equals
  283. * @memberOf Query
  284. * @instance
  285. * @param {Object} val
  286. * @return {Query} this
  287. * @api public
  288. */
  289. /**
  290. * Specifies arguments for an `$or` condition.
  291. *
  292. * ####Example
  293. *
  294. * query.or([{ color: 'red' }, { status: 'emergency' }])
  295. *
  296. * @see $or http://docs.mongodb.org/manual/reference/operator/or/
  297. * @method or
  298. * @memberOf Query
  299. * @instance
  300. * @param {Array} array array of conditions
  301. * @return {Query} this
  302. * @api public
  303. */
  304. /**
  305. * Specifies arguments for a `$nor` condition.
  306. *
  307. * ####Example
  308. *
  309. * query.nor([{ color: 'green' }, { status: 'ok' }])
  310. *
  311. * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/
  312. * @method nor
  313. * @memberOf Query
  314. * @instance
  315. * @param {Array} array array of conditions
  316. * @return {Query} this
  317. * @api public
  318. */
  319. /**
  320. * Specifies arguments for a `$and` condition.
  321. *
  322. * ####Example
  323. *
  324. * query.and([{ color: 'green' }, { status: 'ok' }])
  325. *
  326. * @method and
  327. * @memberOf Query
  328. * @instance
  329. * @see $and http://docs.mongodb.org/manual/reference/operator/and/
  330. * @param {Array} array array of conditions
  331. * @return {Query} this
  332. * @api public
  333. */
  334. /**
  335. * Specifies a $gt query condition.
  336. *
  337. * When called with one argument, the most recent path passed to `where()` is used.
  338. *
  339. * ####Example
  340. *
  341. * Thing.find().where('age').gt(21)
  342. *
  343. * // or
  344. * Thing.find().gt('age', 21)
  345. *
  346. * @method gt
  347. * @memberOf Query
  348. * @instance
  349. * @param {String} [path]
  350. * @param {Number} val
  351. * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/
  352. * @api public
  353. */
  354. /**
  355. * Specifies a $gte query condition.
  356. *
  357. * When called with one argument, the most recent path passed to `where()` is used.
  358. *
  359. * @method gte
  360. * @memberOf Query
  361. * @instance
  362. * @param {String} [path]
  363. * @param {Number} val
  364. * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/
  365. * @api public
  366. */
  367. /**
  368. * Specifies a $lt query condition.
  369. *
  370. * When called with one argument, the most recent path passed to `where()` is used.
  371. *
  372. * @method lt
  373. * @memberOf Query
  374. * @instance
  375. * @param {String} [path]
  376. * @param {Number} val
  377. * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/
  378. * @api public
  379. */
  380. /**
  381. * Specifies a $lte query condition.
  382. *
  383. * When called with one argument, the most recent path passed to `where()` is used.
  384. *
  385. * @method lte
  386. * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/
  387. * @memberOf Query
  388. * @instance
  389. * @param {String} [path]
  390. * @param {Number} val
  391. * @api public
  392. */
  393. /**
  394. * Specifies a $ne query condition.
  395. *
  396. * When called with one argument, the most recent path passed to `where()` is used.
  397. *
  398. * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/
  399. * @method ne
  400. * @memberOf Query
  401. * @instance
  402. * @param {String} [path]
  403. * @param {Number} val
  404. * @api public
  405. */
  406. /**
  407. * Specifies an $in query condition.
  408. *
  409. * When called with one argument, the most recent path passed to `where()` is used.
  410. *
  411. * @see $in http://docs.mongodb.org/manual/reference/operator/in/
  412. * @method in
  413. * @memberOf Query
  414. * @instance
  415. * @param {String} [path]
  416. * @param {Number} val
  417. * @api public
  418. */
  419. /**
  420. * Specifies an $nin query condition.
  421. *
  422. * When called with one argument, the most recent path passed to `where()` is used.
  423. *
  424. * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/
  425. * @method nin
  426. * @memberOf Query
  427. * @instance
  428. * @param {String} [path]
  429. * @param {Number} val
  430. * @api public
  431. */
  432. /**
  433. * Specifies an $all query condition.
  434. *
  435. * When called with one argument, the most recent path passed to `where()` is used.
  436. *
  437. * @see $all http://docs.mongodb.org/manual/reference/operator/all/
  438. * @method all
  439. * @memberOf Query
  440. * @instance
  441. * @param {String} [path]
  442. * @param {Number} val
  443. * @api public
  444. */
  445. /**
  446. * Specifies a $size query condition.
  447. *
  448. * When called with one argument, the most recent path passed to `where()` is used.
  449. *
  450. * ####Example
  451. *
  452. * MyModel.where('tags').size(0).exec(function (err, docs) {
  453. * if (err) return handleError(err);
  454. *
  455. * assert(Array.isArray(docs));
  456. * console.log('documents with 0 tags', docs);
  457. * })
  458. *
  459. * @see $size http://docs.mongodb.org/manual/reference/operator/size/
  460. * @method size
  461. * @memberOf Query
  462. * @instance
  463. * @param {String} [path]
  464. * @param {Number} val
  465. * @api public
  466. */
  467. /**
  468. * Specifies a $regex query condition.
  469. *
  470. * When called with one argument, the most recent path passed to `where()` is used.
  471. *
  472. * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/
  473. * @method regex
  474. * @memberOf Query
  475. * @instance
  476. * @param {String} [path]
  477. * @param {String|RegExp} val
  478. * @api public
  479. */
  480. /**
  481. * Specifies a $maxDistance query condition.
  482. *
  483. * When called with one argument, the most recent path passed to `where()` is used.
  484. *
  485. * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
  486. * @method maxDistance
  487. * @memberOf Query
  488. * @instance
  489. * @param {String} [path]
  490. * @param {Number} val
  491. * @api public
  492. */
  493. /**
  494. * Specifies a `$mod` condition, filters documents for documents whose
  495. * `path` property is a number that is equal to `remainder` modulo `divisor`.
  496. *
  497. * ####Example
  498. *
  499. * // All find products whose inventory is odd
  500. * Product.find().mod('inventory', [2, 1]);
  501. * Product.find().where('inventory').mod([2, 1]);
  502. * // This syntax is a little strange, but supported.
  503. * Product.find().where('inventory').mod(2, 1);
  504. *
  505. * @method mod
  506. * @memberOf Query
  507. * @instance
  508. * @param {String} [path]
  509. * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`.
  510. * @return {Query} this
  511. * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/
  512. * @api public
  513. */
  514. Query.prototype.mod = function() {
  515. let val;
  516. let path;
  517. if (arguments.length === 1) {
  518. this._ensurePath('mod');
  519. val = arguments[0];
  520. path = this._path;
  521. } else if (arguments.length === 2 && !Array.isArray(arguments[1])) {
  522. this._ensurePath('mod');
  523. val = slice(arguments);
  524. path = this._path;
  525. } else if (arguments.length === 3) {
  526. val = slice(arguments, 1);
  527. path = arguments[0];
  528. } else {
  529. val = arguments[1];
  530. path = arguments[0];
  531. }
  532. const conds = this._conditions[path] || (this._conditions[path] = {});
  533. conds.$mod = val;
  534. return this;
  535. };
  536. /**
  537. * Specifies an `$exists` condition
  538. *
  539. * ####Example
  540. *
  541. * // { name: { $exists: true }}
  542. * Thing.where('name').exists()
  543. * Thing.where('name').exists(true)
  544. * Thing.find().exists('name')
  545. *
  546. * // { name: { $exists: false }}
  547. * Thing.where('name').exists(false);
  548. * Thing.find().exists('name', false);
  549. *
  550. * @method exists
  551. * @memberOf Query
  552. * @instance
  553. * @param {String} [path]
  554. * @param {Number} val
  555. * @return {Query} this
  556. * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/
  557. * @api public
  558. */
  559. /**
  560. * Specifies an `$elemMatch` condition
  561. *
  562. * ####Example
  563. *
  564. * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
  565. *
  566. * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
  567. *
  568. * query.elemMatch('comment', function (elem) {
  569. * elem.where('author').equals('autobot');
  570. * elem.where('votes').gte(5);
  571. * })
  572. *
  573. * query.where('comment').elemMatch(function (elem) {
  574. * elem.where({ author: 'autobot' });
  575. * elem.where('votes').gte(5);
  576. * })
  577. *
  578. * @method elemMatch
  579. * @memberOf Query
  580. * @instance
  581. * @param {String|Object|Function} path
  582. * @param {Object|Function} criteria
  583. * @return {Query} this
  584. * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/
  585. * @api public
  586. */
  587. /**
  588. * Defines a `$within` or `$geoWithin` argument for geo-spatial queries.
  589. *
  590. * ####Example
  591. *
  592. * query.where(path).within().box()
  593. * query.where(path).within().circle()
  594. * query.where(path).within().geometry()
  595. *
  596. * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
  597. * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
  598. * query.where('loc').within({ polygon: [[],[],[],[]] });
  599. *
  600. * query.where('loc').within([], [], []) // polygon
  601. * query.where('loc').within([], []) // box
  602. * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
  603. *
  604. * **MUST** be used after `where()`.
  605. *
  606. * ####NOTE:
  607. *
  608. * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin).
  609. *
  610. * ####NOTE:
  611. *
  612. * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
  613. *
  614. * @method within
  615. * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
  616. * @see $box http://docs.mongodb.org/manual/reference/operator/box/
  617. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  618. * @see $center http://docs.mongodb.org/manual/reference/operator/center/
  619. * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
  620. * @memberOf Query
  621. * @instance
  622. * @return {Query} this
  623. * @api public
  624. */
  625. /**
  626. * Specifies a $slice projection for an array.
  627. *
  628. * ####Example
  629. *
  630. * query.slice('comments', 5)
  631. * query.slice('comments', -5)
  632. * query.slice('comments', [10, 5])
  633. * query.where('comments').slice(5)
  634. * query.where('comments').slice([-10, 5])
  635. *
  636. * @method slice
  637. * @memberOf Query
  638. * @instance
  639. * @param {String} [path]
  640. * @param {Number} val number/range of elements to slice
  641. * @return {Query} this
  642. * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
  643. * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice
  644. * @api public
  645. */
  646. /**
  647. * Specifies the maximum number of documents the query will return.
  648. *
  649. * ####Example
  650. *
  651. * query.limit(20)
  652. *
  653. * ####Note
  654. *
  655. * Cannot be used with `distinct()`
  656. *
  657. * @method limit
  658. * @memberOf Query
  659. * @instance
  660. * @param {Number} val
  661. * @api public
  662. */
  663. /**
  664. * Specifies the number of documents to skip.
  665. *
  666. * ####Example
  667. *
  668. * query.skip(100).limit(20)
  669. *
  670. * ####Note
  671. *
  672. * Cannot be used with `distinct()`
  673. *
  674. * @method skip
  675. * @memberOf Query
  676. * @instance
  677. * @param {Number} val
  678. * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/
  679. * @api public
  680. */
  681. /**
  682. * Specifies the maxScan option.
  683. *
  684. * ####Example
  685. *
  686. * query.maxScan(100)
  687. *
  688. * ####Note
  689. *
  690. * Cannot be used with `distinct()`
  691. *
  692. * @method maxScan
  693. * @memberOf Query
  694. * @instance
  695. * @param {Number} val
  696. * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/
  697. * @api public
  698. */
  699. /**
  700. * Specifies the batchSize option.
  701. *
  702. * ####Example
  703. *
  704. * query.batchSize(100)
  705. *
  706. * ####Note
  707. *
  708. * Cannot be used with `distinct()`
  709. *
  710. * @method batchSize
  711. * @memberOf Query
  712. * @instance
  713. * @param {Number} val
  714. * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/
  715. * @api public
  716. */
  717. /**
  718. * Specifies the `comment` option.
  719. *
  720. * ####Example
  721. *
  722. * query.comment('login query')
  723. *
  724. * ####Note
  725. *
  726. * Cannot be used with `distinct()`
  727. *
  728. * @method comment
  729. * @memberOf Query
  730. * @instance
  731. * @param {Number} val
  732. * @see comment http://docs.mongodb.org/manual/reference/operator/comment/
  733. * @api public
  734. */
  735. /**
  736. * Specifies this query as a `snapshot` query.
  737. *
  738. * ####Example
  739. *
  740. * query.snapshot() // true
  741. * query.snapshot(true)
  742. * query.snapshot(false)
  743. *
  744. * ####Note
  745. *
  746. * Cannot be used with `distinct()`
  747. *
  748. * @method snapshot
  749. * @memberOf Query
  750. * @instance
  751. * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/
  752. * @return {Query} this
  753. * @api public
  754. */
  755. /**
  756. * Sets query hints.
  757. *
  758. * ####Example
  759. *
  760. * query.hint({ indexA: 1, indexB: -1})
  761. *
  762. * ####Note
  763. *
  764. * Cannot be used with `distinct()`
  765. *
  766. * @method hint
  767. * @memberOf Query
  768. * @instance
  769. * @param {Object} val a hint object
  770. * @return {Query} this
  771. * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/
  772. * @api public
  773. */
  774. /**
  775. * Specifies which document fields to include or exclude (also known as the query "projection")
  776. *
  777. * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select).
  778. *
  779. * A projection _must_ be either inclusive or exclusive. In other words, you must
  780. * either list the fields to include (which excludes all others), or list the fields
  781. * to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field).
  782. *
  783. * ####Example
  784. *
  785. * // include a and b, exclude other fields
  786. * query.select('a b');
  787. *
  788. * // exclude c and d, include other fields
  789. * query.select('-c -d');
  790. *
  791. * // Use `+` to override schema-level `select: false` without making the
  792. * // projection inclusive.
  793. * const schema = new Schema({
  794. * foo: { type: String, select: false },
  795. * bar: String
  796. * });
  797. * // ...
  798. * query.select('+foo'); // Override foo's `select: false` without excluding `bar`
  799. *
  800. * // or you may use object notation, useful when
  801. * // you have keys already prefixed with a "-"
  802. * query.select({ a: 1, b: 1 });
  803. * query.select({ c: 0, d: 0 });
  804. *
  805. *
  806. * @method select
  807. * @memberOf Query
  808. * @instance
  809. * @param {Object|String} arg
  810. * @return {Query} this
  811. * @see SchemaType
  812. * @api public
  813. */
  814. Query.prototype.select = function select() {
  815. let arg = arguments[0];
  816. if (!arg) return this;
  817. let i;
  818. let len;
  819. if (arguments.length !== 1) {
  820. throw new Error('Invalid select: select only takes 1 argument');
  821. }
  822. this._validate('select');
  823. const fields = this._fields || (this._fields = {});
  824. const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {});
  825. const type = typeof arg;
  826. if (('string' == type || Object.prototype.toString.call(arg) === '[object Arguments]') &&
  827. 'number' == typeof arg.length || Array.isArray(arg)) {
  828. if ('string' == type)
  829. arg = arg.split(/\s+/);
  830. for (i = 0, len = arg.length; i < len; ++i) {
  831. let field = arg[i];
  832. if (!field) continue;
  833. const include = '-' == field[0] ? 0 : 1;
  834. if (include === 0) field = field.substring(1);
  835. fields[field] = include;
  836. userProvidedFields[field] = include;
  837. }
  838. return this;
  839. }
  840. if (utils.isObject(arg)) {
  841. const keys = Object.keys(arg);
  842. for (i = 0; i < keys.length; ++i) {
  843. fields[keys[i]] = arg[keys[i]];
  844. userProvidedFields[keys[i]] = arg[keys[i]];
  845. }
  846. return this;
  847. }
  848. throw new TypeError('Invalid select() argument. Must be string or object.');
  849. };
  850. /**
  851. * _DEPRECATED_ Sets the slaveOk option.
  852. *
  853. * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read).
  854. *
  855. * ####Example:
  856. *
  857. * query.slaveOk() // true
  858. * query.slaveOk(true)
  859. * query.slaveOk(false)
  860. *
  861. * @method slaveOk
  862. * @memberOf Query
  863. * @instance
  864. * @deprecated use read() preferences instead if on mongodb >= 2.2
  865. * @param {Boolean} v defaults to true
  866. * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
  867. * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/
  868. * @see read() #query_Query-read
  869. * @return {Query} this
  870. * @api public
  871. */
  872. /**
  873. * Determines the MongoDB nodes from which to read.
  874. *
  875. * ####Preferences:
  876. *
  877. * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
  878. * secondary Read from secondary if available, otherwise error.
  879. * primaryPreferred Read from primary if available, otherwise a secondary.
  880. * secondaryPreferred Read from a secondary if available, otherwise read from the primary.
  881. * 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.
  882. *
  883. * Aliases
  884. *
  885. * p primary
  886. * pp primaryPreferred
  887. * s secondary
  888. * sp secondaryPreferred
  889. * n nearest
  890. *
  891. * ####Example:
  892. *
  893. * new Query().read('primary')
  894. * new Query().read('p') // same as primary
  895. *
  896. * new Query().read('primaryPreferred')
  897. * new Query().read('pp') // same as primaryPreferred
  898. *
  899. * new Query().read('secondary')
  900. * new Query().read('s') // same as secondary
  901. *
  902. * new Query().read('secondaryPreferred')
  903. * new Query().read('sp') // same as secondaryPreferred
  904. *
  905. * new Query().read('nearest')
  906. * new Query().read('n') // same as nearest
  907. *
  908. * // read from secondaries with matching tags
  909. * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
  910. *
  911. * Read more about how to use read preferrences [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).
  912. *
  913. * @method read
  914. * @memberOf Query
  915. * @instance
  916. * @param {String} pref one of the listed preference options or aliases
  917. * @param {Array} [tags] optional tags for this query
  918. * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference
  919. * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences
  920. * @return {Query} this
  921. * @api public
  922. */
  923. Query.prototype.read = function read(pref, tags) {
  924. // first cast into a ReadPreference object to support tags
  925. const read = new ReadPreference(pref, tags);
  926. this.options.readPreference = read;
  927. return this;
  928. };
  929. /**
  930. * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/)
  931. * associated with this query. Sessions are how you mark a query as part of a
  932. * [transaction](/docs/transactions.html).
  933. *
  934. * Calling `session(null)` removes the session from this query.
  935. *
  936. * ####Example:
  937. *
  938. * const s = await mongoose.startSession();
  939. * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s);
  940. *
  941. * @method session
  942. * @memberOf Query
  943. * @instance
  944. * @param {ClientSession} [session] from `await conn.startSession()`
  945. * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession
  946. * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession
  947. * @return {Query} this
  948. * @api public
  949. */
  950. Query.prototype.session = function session(v) {
  951. if (v == null) {
  952. delete this.options.session;
  953. }
  954. this.options.session = v;
  955. return this;
  956. };
  957. /**
  958. * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
  959. * that must acknowledge this write before this write is considered successful.
  960. * This option is only valid for operations that write to the database:
  961. *
  962. * - `deleteOne()`
  963. * - `deleteMany()`
  964. * - `findOneAndDelete()`
  965. * - `findOneAndReplace()`
  966. * - `findOneAndUpdate()`
  967. * - `remove()`
  968. * - `update()`
  969. * - `updateOne()`
  970. * - `updateMany()`
  971. *
  972. * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern)
  973. *
  974. * ####Example:
  975. *
  976. * // The 'majority' option means the `deleteOne()` promise won't resolve
  977. * // until the `deleteOne()` has propagated to the majority of the replica set
  978. * await mongoose.model('Person').
  979. * deleteOne({ name: 'Ned Stark' }).
  980. * w('majority');
  981. *
  982. * @method w
  983. * @memberOf Query
  984. * @instance
  985. * @param {String|number} val 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).
  986. * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option
  987. * @return {Query} this
  988. * @api public
  989. */
  990. Query.prototype.w = function w(val) {
  991. if (val == null) {
  992. delete this.options.w;
  993. }
  994. this.options.w = val;
  995. return this;
  996. };
  997. /**
  998. * Requests acknowledgement that this operation has been persisted to MongoDB's
  999. * on-disk journal.
  1000. * This option is only valid for operations that write to the database:
  1001. *
  1002. * - `deleteOne()`
  1003. * - `deleteMany()`
  1004. * - `findOneAndDelete()`
  1005. * - `findOneAndReplace()`
  1006. * - `findOneAndUpdate()`
  1007. * - `remove()`
  1008. * - `update()`
  1009. * - `updateOne()`
  1010. * - `updateMany()`
  1011. *
  1012. * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern)
  1013. *
  1014. * ####Example:
  1015. *
  1016. * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true);
  1017. *
  1018. * @method j
  1019. * @memberOf Query
  1020. * @instance
  1021. * @param {boolean} val
  1022. * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option
  1023. * @return {Query} this
  1024. * @api public
  1025. */
  1026. Query.prototype.j = function j(val) {
  1027. if (val == null) {
  1028. delete this.options.j;
  1029. }
  1030. this.options.j = val;
  1031. return this;
  1032. };
  1033. /**
  1034. * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to
  1035. * wait for this write to propagate through the replica set before this
  1036. * operation fails. The default is `0`, which means no timeout.
  1037. *
  1038. * This option is only valid for operations that write to the database:
  1039. *
  1040. * - `deleteOne()`
  1041. * - `deleteMany()`
  1042. * - `findOneAndDelete()`
  1043. * - `findOneAndReplace()`
  1044. * - `findOneAndUpdate()`
  1045. * - `remove()`
  1046. * - `update()`
  1047. * - `updateOne()`
  1048. * - `updateMany()`
  1049. *
  1050. * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern)
  1051. *
  1052. * ####Example:
  1053. *
  1054. * // The `deleteOne()` promise won't resolve until this `deleteOne()` has
  1055. * // propagated to at least `w = 2` members of the replica set. If it takes
  1056. * // longer than 1 second, this `deleteOne()` will fail.
  1057. * await mongoose.model('Person').
  1058. * deleteOne({ name: 'Ned Stark' }).
  1059. * w(2).
  1060. * wtimeout(1000);
  1061. *
  1062. * @method wtimeout
  1063. * @memberOf Query
  1064. * @instance
  1065. * @param {number} ms number of milliseconds to wait
  1066. * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout
  1067. * @return {Query} this
  1068. * @api public
  1069. */
  1070. Query.prototype.wtimeout = function wtimeout(ms) {
  1071. if (ms == null) {
  1072. delete this.options.wtimeout;
  1073. }
  1074. this.options.wtimeout = ms;
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets the readConcern option for the query.
  1079. *
  1080. * ####Example:
  1081. *
  1082. * new Query().readConcern('local')
  1083. * new Query().readConcern('l') // same as local
  1084. *
  1085. * new Query().readConcern('available')
  1086. * new Query().readConcern('a') // same as available
  1087. *
  1088. * new Query().readConcern('majority')
  1089. * new Query().readConcern('m') // same as majority
  1090. *
  1091. * new Query().readConcern('linearizable')
  1092. * new Query().readConcern('lz') // same as linearizable
  1093. *
  1094. * new Query().readConcern('snapshot')
  1095. * new Query().readConcern('s') // same as snapshot
  1096. *
  1097. *
  1098. * ####Read Concern Level:
  1099. *
  1100. * 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).
  1101. * 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).
  1102. * 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.
  1103. * 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.
  1104. * 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.
  1105. *
  1106. * Aliases
  1107. *
  1108. * l local
  1109. * a available
  1110. * m majority
  1111. * lz linearizable
  1112. * s snapshot
  1113. *
  1114. * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/).
  1115. *
  1116. * @memberOf Query
  1117. * @method readConcern
  1118. * @param {String} level one of the listed read concern level or their aliases
  1119. * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/
  1120. * @return {Query} this
  1121. * @api public
  1122. */
  1123. /**
  1124. * Merges another Query or conditions object into this one.
  1125. *
  1126. * When a Query is passed, conditions, field selection and options are merged.
  1127. *
  1128. * New in 3.7.0
  1129. *
  1130. * @method merge
  1131. * @memberOf Query
  1132. * @instance
  1133. * @param {Query|Object} source
  1134. * @return {Query} this
  1135. */
  1136. /**
  1137. * Gets query options.
  1138. *
  1139. * ####Example:
  1140. *
  1141. * var query = new Query();
  1142. * query.limit(10);
  1143. * query.setOptions({ maxTimeMS: 1000 })
  1144. * query.getOptions(); // { limit: 10, maxTimeMS: 1000 }
  1145. *
  1146. * @return {Object} the options
  1147. * @api public
  1148. */
  1149. Query.prototype.getOptions = function() {
  1150. return this.options;
  1151. };
  1152. /**
  1153. * Sets query options. Some options only make sense for certain operations.
  1154. *
  1155. * ####Options:
  1156. *
  1157. * The following options are only for `find()`:
  1158. *
  1159. * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors)
  1160. * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D)
  1161. * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D)
  1162. * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D)
  1163. * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan)
  1164. * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D)
  1165. * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment)
  1166. * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D)
  1167. * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference)
  1168. * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint)
  1169. *
  1170. * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
  1171. *
  1172. * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
  1173. * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/)
  1174. * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options.
  1175. *
  1176. * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`:
  1177. *
  1178. * - [lean](./api.html#query_Query-lean)
  1179. *
  1180. * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`:
  1181. *
  1182. * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/)
  1183. *
  1184. * The following options are for all operations:
  1185. *
  1186. * - [collation](https://docs.mongodb.com/manual/reference/collation/)
  1187. * - [session](https://docs.mongodb.com/manual/reference/server-sessions/)
  1188. *
  1189. * @param {Object} options
  1190. * @return {Query} this
  1191. * @api public
  1192. */
  1193. Query.prototype.setOptions = function(options, overwrite) {
  1194. // overwrite is only for internal use
  1195. if (overwrite) {
  1196. // ensure that _mongooseOptions & options are two different objects
  1197. this._mongooseOptions = (options && utils.clone(options)) || {};
  1198. this.options = options || {};
  1199. if ('populate' in options) {
  1200. this.populate(this._mongooseOptions);
  1201. }
  1202. return this;
  1203. }
  1204. if (options == null) {
  1205. return this;
  1206. }
  1207. if (typeof options !== 'object') {
  1208. throw new Error('Options must be an object, got "' + options + '"');
  1209. }
  1210. if (Array.isArray(options.populate)) {
  1211. const populate = options.populate;
  1212. delete options.populate;
  1213. const _numPopulate = populate.length;
  1214. for (let i = 0; i < _numPopulate; ++i) {
  1215. this.populate(populate[i]);
  1216. }
  1217. }
  1218. if ('useFindAndModify' in options) {
  1219. this._mongooseOptions.useFindAndModify = options.useFindAndModify;
  1220. delete options.useFindAndModify;
  1221. }
  1222. if ('omitUndefined' in options) {
  1223. this._mongooseOptions.omitUndefined = options.omitUndefined;
  1224. delete options.omitUndefined;
  1225. }
  1226. return Query.base.setOptions.call(this, options);
  1227. };
  1228. /**
  1229. * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
  1230. * which makes this query return detailed execution stats instead of the actual
  1231. * query result. This method is useful for determining what index your queries
  1232. * use.
  1233. *
  1234. * Calling `query.explain(v)` is equivalent to `query.setOption({ explain: v })`
  1235. *
  1236. * ####Example:
  1237. *
  1238. * const query = new Query();
  1239. * const res = await query.find({ a: 1 }).explain('queryPlanner');
  1240. * console.log(res);
  1241. *
  1242. * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner'
  1243. * @return {Query} this
  1244. * @api public
  1245. */
  1246. Query.prototype.explain = function(verbose) {
  1247. if (arguments.length === 0) {
  1248. this.options.explain = true;
  1249. return this;
  1250. }
  1251. this.options.explain = verbose;
  1252. return this;
  1253. };
  1254. /**
  1255. * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/)
  1256. * option. This will tell the MongoDB server to abort if the query or write op
  1257. * has been running for more than `ms` milliseconds.
  1258. *
  1259. * Calling `query.maxTimeMS(v)` is equivalent to `query.setOption({ maxTimeMS: v })`
  1260. *
  1261. * ####Example:
  1262. *
  1263. * const query = new Query();
  1264. * // Throws an error 'operation exceeded time limit' as long as there's
  1265. * // >= 1 doc in the queried collection
  1266. * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100);
  1267. *
  1268. * @param {Number} [ms] The number of milliseconds
  1269. * @return {Query} this
  1270. * @api public
  1271. */
  1272. Query.prototype.maxTimeMS = function(ms) {
  1273. this.options.maxTimeMS = ms;
  1274. return this;
  1275. };
  1276. /**
  1277. * Returns the current query conditions as a JSON object.
  1278. *
  1279. * ####Example:
  1280. *
  1281. * var query = new Query();
  1282. * query.find({ a: 1 }).where('b').gt(2);
  1283. * query.getQuery(); // { a: 1, b: { $gt: 2 } }
  1284. *
  1285. * @return {Object} current query conditions
  1286. * @api public
  1287. */
  1288. Query.prototype.getQuery = function() {
  1289. return this._conditions;
  1290. };
  1291. /**
  1292. * Sets the query conditions to the provided JSON object.
  1293. *
  1294. * ####Example:
  1295. *
  1296. * var query = new Query();
  1297. * query.find({ a: 1 })
  1298. * query.setQuery({ a: 2 });
  1299. * query.getQuery(); // { a: 2 }
  1300. *
  1301. * @param {Object} new query conditions
  1302. * @return {undefined}
  1303. * @api public
  1304. */
  1305. Query.prototype.setQuery = function(val) {
  1306. this._conditions = val;
  1307. };
  1308. /**
  1309. * Returns the current update operations as a JSON object.
  1310. *
  1311. * ####Example:
  1312. *
  1313. * var query = new Query();
  1314. * query.update({}, { $set: { a: 5 } });
  1315. * query.getUpdate(); // { $set: { a: 5 } }
  1316. *
  1317. * @return {Object} current update operations
  1318. * @api public
  1319. */
  1320. Query.prototype.getUpdate = function() {
  1321. return this._update;
  1322. };
  1323. /**
  1324. * Sets the current update operation to new value.
  1325. *
  1326. * ####Example:
  1327. *
  1328. * var query = new Query();
  1329. * query.update({}, { $set: { a: 5 } });
  1330. * query.setUpdate({ $set: { b: 6 } });
  1331. * query.getUpdate(); // { $set: { b: 6 } }
  1332. *
  1333. * @param {Object} new update operation
  1334. * @return {undefined}
  1335. * @api public
  1336. */
  1337. Query.prototype.setUpdate = function(val) {
  1338. this._update = val;
  1339. };
  1340. /**
  1341. * Returns fields selection for this query.
  1342. *
  1343. * @method _fieldsForExec
  1344. * @return {Object}
  1345. * @api private
  1346. * @receiver Query
  1347. */
  1348. Query.prototype._fieldsForExec = function() {
  1349. return utils.clone(this._fields);
  1350. };
  1351. /**
  1352. * Return an update document with corrected $set operations.
  1353. *
  1354. * @method _updateForExec
  1355. * @api private
  1356. * @receiver Query
  1357. */
  1358. Query.prototype._updateForExec = function() {
  1359. const update = utils.clone(this._update, {
  1360. transform: false,
  1361. depopulate: true
  1362. });
  1363. const ops = Object.keys(update);
  1364. let i = ops.length;
  1365. const ret = {};
  1366. while (i--) {
  1367. const op = ops[i];
  1368. if (this.options.overwrite) {
  1369. ret[op] = update[op];
  1370. continue;
  1371. }
  1372. if ('$' !== op[0]) {
  1373. // fix up $set sugar
  1374. if (!ret.$set) {
  1375. if (update.$set) {
  1376. ret.$set = update.$set;
  1377. } else {
  1378. ret.$set = {};
  1379. }
  1380. }
  1381. ret.$set[op] = update[op];
  1382. ops.splice(i, 1);
  1383. if (!~ops.indexOf('$set')) ops.push('$set');
  1384. } else if ('$set' === op) {
  1385. if (!ret.$set) {
  1386. ret[op] = update[op];
  1387. }
  1388. } else {
  1389. ret[op] = update[op];
  1390. }
  1391. }
  1392. return ret;
  1393. };
  1394. /**
  1395. * Makes sure _path is set.
  1396. *
  1397. * @method _ensurePath
  1398. * @param {String} method
  1399. * @api private
  1400. * @receiver Query
  1401. */
  1402. /**
  1403. * Determines if `conds` can be merged using `mquery().merge()`
  1404. *
  1405. * @method canMerge
  1406. * @memberOf Query
  1407. * @instance
  1408. * @param {Object} conds
  1409. * @return {Boolean}
  1410. * @api private
  1411. */
  1412. /**
  1413. * Returns default options for this query.
  1414. *
  1415. * @param {Model} model
  1416. * @api private
  1417. */
  1418. Query.prototype._optionsForExec = function(model) {
  1419. const options = utils.clone(this.options);
  1420. delete options.populate;
  1421. model = model || this.model;
  1422. if (!model) {
  1423. return options;
  1424. }
  1425. const safe = get(model, 'schema.options.safe', null);
  1426. if (!('safe' in options) && safe != null) {
  1427. setSafe(options, safe);
  1428. }
  1429. // Apply schema-level `writeConcern` option
  1430. applyWriteConcern(model.schema, options);
  1431. const readPreference = get(model, 'schema.options.read');
  1432. if (!('readPreference' in options) && readPreference) {
  1433. options.readPreference = readPreference;
  1434. }
  1435. if (options.upsert !== void 0) {
  1436. options.upsert = !!options.upsert;
  1437. }
  1438. return options;
  1439. };
  1440. /*!
  1441. * ignore
  1442. */
  1443. const safeDeprecationWarning = 'Mongoose: the `safe` option is deprecated. ' +
  1444. 'Use write concerns instead: http://bit.ly/mongoose-w';
  1445. const setSafe = util.deprecate(function setSafe(options, safe) {
  1446. options.safe = safe;
  1447. }, safeDeprecationWarning);
  1448. /**
  1449. * Sets the lean option.
  1450. *
  1451. * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied.
  1452. *
  1453. * ####Example:
  1454. *
  1455. * new Query().lean() // true
  1456. * new Query().lean(true)
  1457. * new Query().lean(false)
  1458. *
  1459. * Model.find().lean().exec(function (err, docs) {
  1460. * docs[0] instanceof mongoose.Document // false
  1461. * });
  1462. *
  1463. * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream).
  1464. *
  1465. * @param {Boolean|Object} bool defaults to true
  1466. * @return {Query} this
  1467. * @api public
  1468. */
  1469. Query.prototype.lean = function(v) {
  1470. this._mongooseOptions.lean = arguments.length ? v : true;
  1471. return this;
  1472. };
  1473. /**
  1474. * Adds a `$set` to this query's update without changing the operation.
  1475. * This is useful for query middleware so you can add an update regardless
  1476. * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc.
  1477. *
  1478. * ####Example:
  1479. *
  1480. * // Updates `{ $set: { updatedAt: new Date() } }`
  1481. * new Query().updateOne({}, {}).set('updatedAt', new Date());
  1482. * new Query().updateMany({}, {}).set({ updatedAt: new Date() });
  1483. *
  1484. * @param {String|Object} path path or object of key/value pairs to set
  1485. * @param {Any} [val] the value to set
  1486. * @return {Query} this
  1487. * @api public
  1488. */
  1489. Query.prototype.set = function(path, val) {
  1490. if (typeof path === 'object') {
  1491. const keys = Object.keys(path);
  1492. for (const key of keys) {
  1493. this.set(key, path[key]);
  1494. }
  1495. return this;
  1496. }
  1497. this._update = this._update || {};
  1498. this._update.$set = this._update.$set || {};
  1499. this._update.$set[path] = val;
  1500. return this;
  1501. };
  1502. /**
  1503. * Gets/sets the error flag on this query. If this flag is not null or
  1504. * undefined, the `exec()` promise will reject without executing.
  1505. *
  1506. * ####Example:
  1507. *
  1508. * Query().error(); // Get current error value
  1509. * Query().error(null); // Unset the current error
  1510. * Query().error(new Error('test')); // `exec()` will resolve with test
  1511. * Schema.pre('find', function() {
  1512. * if (!this.getQuery().userId) {
  1513. * this.error(new Error('Not allowed to query without setting userId'));
  1514. * }
  1515. * });
  1516. *
  1517. * Note that query casting runs **after** hooks, so cast errors will override
  1518. * custom errors.
  1519. *
  1520. * ####Example:
  1521. * var TestSchema = new Schema({ num: Number });
  1522. * var TestModel = db.model('Test', TestSchema);
  1523. * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
  1524. * // `error` will be a cast error because `num` failed to cast
  1525. * });
  1526. *
  1527. * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB
  1528. * @return {Query} this
  1529. * @api public
  1530. */
  1531. Query.prototype.error = function error(err) {
  1532. if (arguments.length === 0) {
  1533. return this._error;
  1534. }
  1535. this._error = err;
  1536. return this;
  1537. };
  1538. /*!
  1539. * ignore
  1540. */
  1541. Query.prototype._unsetCastError = function _unsetCastError() {
  1542. if (this._error != null && !(this._error instanceof CastError)) {
  1543. return;
  1544. }
  1545. return this.error(null);
  1546. };
  1547. /**
  1548. * Getter/setter around the current mongoose-specific options for this query
  1549. * Below are the current Mongoose-specific options.
  1550. *
  1551. * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate)
  1552. * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information.
  1553. * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information.
  1554. * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information.
  1555. * - `useFindAndModify`: used to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#-findandmodify-)
  1556. * - `omitUndefined`: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  1557. * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere)
  1558. *
  1559. * Mongoose maintains a separate object for internal options because
  1560. * Mongoose sends `Query.prototype.options` to the MongoDB server, and the
  1561. * above options are not relevant for the MongoDB server.
  1562. *
  1563. * @param {Object} options if specified, overwrites the current options
  1564. * @return {Object} the options
  1565. * @api public
  1566. */
  1567. Query.prototype.mongooseOptions = function(v) {
  1568. if (arguments.length > 0) {
  1569. this._mongooseOptions = v;
  1570. }
  1571. return this._mongooseOptions;
  1572. };
  1573. /*!
  1574. * ignore
  1575. */
  1576. Query.prototype._castConditions = function() {
  1577. try {
  1578. this.cast(this.model);
  1579. this._unsetCastError();
  1580. } catch (err) {
  1581. this.error(err);
  1582. }
  1583. };
  1584. /**
  1585. * Thunk around find()
  1586. *
  1587. * @param {Function} [callback]
  1588. * @return {Query} this
  1589. * @api private
  1590. */
  1591. Query.prototype._find = wrapThunk(function(callback) {
  1592. this._castConditions();
  1593. if (this.error() != null) {
  1594. callback(this.error());
  1595. return null;
  1596. }
  1597. callback = _wrapThunkCallback(this, callback);
  1598. this._applyPaths();
  1599. this._fields = this._castFields(this._fields);
  1600. const fields = this._fieldsForExec();
  1601. const mongooseOptions = this._mongooseOptions;
  1602. const _this = this;
  1603. const userProvidedFields = _this._userProvidedFields || {};
  1604. // Separate options to pass down to `completeMany()` in case we need to
  1605. // set a session on the document
  1606. const completeManyOptions = Object.assign({}, {
  1607. session: get(this, 'options.session', null)
  1608. });
  1609. const cb = (err, docs) => {
  1610. if (err) {
  1611. return callback(err);
  1612. }
  1613. if (docs.length === 0) {
  1614. return callback(null, docs);
  1615. }
  1616. if (this.options.explain) {
  1617. return callback(null, docs);
  1618. }
  1619. if (!mongooseOptions.populate) {
  1620. return mongooseOptions.lean ?
  1621. callback(null, docs) :
  1622. completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback);
  1623. }
  1624. const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions);
  1625. completeManyOptions.populated = pop;
  1626. _this.model.populate(docs, pop, function(err, docs) {
  1627. if (err) return callback(err);
  1628. return mongooseOptions.lean ?
  1629. callback(null, docs) :
  1630. completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback);
  1631. });
  1632. };
  1633. const options = this._optionsForExec();
  1634. options.projection = this._fieldsForExec();
  1635. const filter = this._conditions;
  1636. this._collection.find(filter, options, cb);
  1637. return null;
  1638. });
  1639. /**
  1640. * Find all documents that match `selector`. The result will be an array of documents.
  1641. *
  1642. * If there are too many documents in the result to fit in memory, use
  1643. * [`Query.prototype.cursor()`](api.html#query_Query-cursor)
  1644. *
  1645. * ####Example
  1646. *
  1647. * // Using async/await
  1648. * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
  1649. *
  1650. * // Using callbacks
  1651. * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});
  1652. *
  1653. * @param {Object} [filter] mongodb selector. If not specified, returns all documents.
  1654. * @param {Function} [callback]
  1655. * @return {Query} this
  1656. * @api public
  1657. */
  1658. Query.prototype.find = function(conditions, callback) {
  1659. if (typeof conditions === 'function') {
  1660. callback = conditions;
  1661. conditions = {};
  1662. }
  1663. conditions = utils.toObject(conditions);
  1664. if (mquery.canMerge(conditions)) {
  1665. this.merge(conditions);
  1666. prepareDiscriminatorCriteria(this);
  1667. } else if (conditions != null) {
  1668. this.error(new ObjectParameterError(conditions, 'filter', 'find'));
  1669. }
  1670. // if we don't have a callback, then just return the query object
  1671. if (!callback) {
  1672. return Query.base.find.call(this);
  1673. }
  1674. this._find(callback);
  1675. return this;
  1676. };
  1677. /**
  1678. * Merges another Query or conditions object into this one.
  1679. *
  1680. * When a Query is passed, conditions, field selection and options are merged.
  1681. *
  1682. * @param {Query|Object} source
  1683. * @return {Query} this
  1684. */
  1685. Query.prototype.merge = function(source) {
  1686. if (!source) {
  1687. return this;
  1688. }
  1689. const opts = { overwrite: true };
  1690. if (source instanceof Query) {
  1691. // if source has a feature, apply it to ourselves
  1692. if (source._conditions) {
  1693. utils.merge(this._conditions, source._conditions, opts);
  1694. }
  1695. if (source._fields) {
  1696. this._fields || (this._fields = {});
  1697. utils.merge(this._fields, source._fields, opts);
  1698. }
  1699. if (source.options) {
  1700. this.options || (this.options = {});
  1701. utils.merge(this.options, source.options, opts);
  1702. }
  1703. if (source._update) {
  1704. this._update || (this._update = {});
  1705. utils.mergeClone(this._update, source._update);
  1706. }
  1707. if (source._distinct) {
  1708. this._distinct = source._distinct;
  1709. }
  1710. return this;
  1711. }
  1712. // plain object
  1713. utils.merge(this._conditions, source, opts);
  1714. return this;
  1715. };
  1716. /**
  1717. * Adds a collation to this op (MongoDB 3.4 and up)
  1718. *
  1719. * @param {Object} value
  1720. * @return {Query} this
  1721. * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation
  1722. * @api public
  1723. */
  1724. Query.prototype.collation = function(value) {
  1725. if (this.options == null) {
  1726. this.options = {};
  1727. }
  1728. this.options.collation = value;
  1729. return this;
  1730. };
  1731. /**
  1732. * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc.
  1733. *
  1734. * @api private
  1735. */
  1736. Query.prototype._completeOne = function(doc, res, callback) {
  1737. if (!doc) {
  1738. return callback(null, null);
  1739. }
  1740. const model = this.model;
  1741. const projection = utils.clone(this._fields);
  1742. const userProvidedFields = this._userProvidedFields || {};
  1743. // `populate`, `lean`
  1744. const mongooseOptions = this._mongooseOptions;
  1745. // `rawResult`
  1746. const options = this.options;
  1747. if (options.explain) {
  1748. return callback(null, doc);
  1749. }
  1750. if (!mongooseOptions.populate) {
  1751. return mongooseOptions.lean ?
  1752. _completeOneLean(doc, res, options, callback) :
  1753. completeOne(model, doc, res, options, projection, userProvidedFields,
  1754. null, callback);
  1755. }
  1756. const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions);
  1757. model.populate(doc, pop, (err, doc) => {
  1758. if (err) {
  1759. return callback(err);
  1760. }
  1761. return mongooseOptions.lean ?
  1762. _completeOneLean(doc, res, options, callback) :
  1763. completeOne(model, doc, res, options, projection, userProvidedFields,
  1764. pop, callback);
  1765. });
  1766. };
  1767. /**
  1768. * Thunk around findOne()
  1769. *
  1770. * @param {Function} [callback]
  1771. * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
  1772. * @api private
  1773. */
  1774. Query.prototype._findOne = wrapThunk(function(callback) {
  1775. this._castConditions();
  1776. if (this.error()) {
  1777. callback(this.error());
  1778. return null;
  1779. }
  1780. this._applyPaths();
  1781. this._fields = this._castFields(this._fields);
  1782. // don't pass in the conditions because we already merged them in
  1783. Query.base.findOne.call(this, {}, (err, doc) => {
  1784. if (err) {
  1785. callback(err);
  1786. return null;
  1787. }
  1788. this._completeOne(doc, null, _wrapThunkCallback(this, callback));
  1789. });
  1790. });
  1791. /**
  1792. * Declares the query a findOne operation. When executed, the first found document is passed to the callback.
  1793. *
  1794. * Passing a `callback` executes the query. The result of the query is a single document.
  1795. *
  1796. * * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
  1797. * mongoose will send an empty `findOne` command to MongoDB, which will return
  1798. * an arbitrary document. If you're querying by `_id`, use `Model.findById()`
  1799. * instead.
  1800. *
  1801. * This function triggers the following middleware.
  1802. *
  1803. * - `findOne()`
  1804. *
  1805. * ####Example
  1806. *
  1807. * var query = Kitten.where({ color: 'white' });
  1808. * query.findOne(function (err, kitten) {
  1809. * if (err) return handleError(err);
  1810. * if (kitten) {
  1811. * // doc may be null if no document matched
  1812. * }
  1813. * });
  1814. *
  1815. * @param {Object} [filter] mongodb selector
  1816. * @param {Object} [projection] optional fields to return
  1817. * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1818. * @param {Function} [callback] optional params are (error, document)
  1819. * @return {Query} this
  1820. * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/
  1821. * @see Query.select #query_Query-select
  1822. * @api public
  1823. */
  1824. Query.prototype.findOne = function(conditions, projection, options, callback) {
  1825. if (typeof conditions === 'function') {
  1826. callback = conditions;
  1827. conditions = null;
  1828. projection = null;
  1829. options = null;
  1830. } else if (typeof projection === 'function') {
  1831. callback = projection;
  1832. options = null;
  1833. projection = null;
  1834. } else if (typeof options === 'function') {
  1835. callback = options;
  1836. options = null;
  1837. }
  1838. // make sure we don't send in the whole Document to merge()
  1839. conditions = utils.toObject(conditions);
  1840. this.op = 'findOne';
  1841. if (options) {
  1842. this.setOptions(options);
  1843. }
  1844. if (projection) {
  1845. this.select(projection);
  1846. }
  1847. if (mquery.canMerge(conditions)) {
  1848. this.merge(conditions);
  1849. prepareDiscriminatorCriteria(this);
  1850. } else if (conditions != null) {
  1851. this.error(new ObjectParameterError(conditions, 'filter', 'findOne'));
  1852. }
  1853. if (!callback) {
  1854. // already merged in the conditions, don't need to send them in.
  1855. return Query.base.findOne.call(this);
  1856. }
  1857. this._findOne(callback);
  1858. return this;
  1859. };
  1860. /**
  1861. * Thunk around count()
  1862. *
  1863. * @param {Function} [callback]
  1864. * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
  1865. * @api private
  1866. */
  1867. Query.prototype._count = wrapThunk(function(callback) {
  1868. try {
  1869. this.cast(this.model);
  1870. } catch (err) {
  1871. this.error(err);
  1872. }
  1873. if (this.error()) {
  1874. return callback(this.error());
  1875. }
  1876. const conds = this._conditions;
  1877. const options = this._optionsForExec();
  1878. this._collection.count(conds, options, utils.tick(callback));
  1879. });
  1880. /**
  1881. * Thunk around countDocuments()
  1882. *
  1883. * @param {Function} [callback]
  1884. * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments
  1885. * @api private
  1886. */
  1887. Query.prototype._countDocuments = wrapThunk(function(callback) {
  1888. try {
  1889. this.cast(this.model);
  1890. } catch (err) {
  1891. this.error(err);
  1892. }
  1893. if (this.error()) {
  1894. return callback(this.error());
  1895. }
  1896. const conds = this._conditions;
  1897. const options = this._optionsForExec();
  1898. this._collection.collection.countDocuments(conds, options, utils.tick(callback));
  1899. });
  1900. /**
  1901. * Thunk around estimatedDocumentCount()
  1902. *
  1903. * @param {Function} [callback]
  1904. * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount
  1905. * @api private
  1906. */
  1907. Query.prototype._estimatedDocumentCount = wrapThunk(function(callback) {
  1908. if (this.error()) {
  1909. return callback(this.error());
  1910. }
  1911. const options = this._optionsForExec();
  1912. this._collection.collection.estimatedDocumentCount(options, utils.tick(callback));
  1913. });
  1914. /**
  1915. * Specifies this query as a `count` query.
  1916. *
  1917. * This method is deprecated. If you want to count the number of documents in
  1918. * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount)
  1919. * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead.
  1920. *
  1921. * Passing a `callback` executes the query.
  1922. *
  1923. * This function triggers the following middleware.
  1924. *
  1925. * - `count()`
  1926. *
  1927. * ####Example:
  1928. *
  1929. * var countQuery = model.where({ 'color': 'black' }).count();
  1930. *
  1931. * query.count({ color: 'black' }).count(callback)
  1932. *
  1933. * query.count({ color: 'black' }, callback)
  1934. *
  1935. * query.where('color', 'black').count(function (err, count) {
  1936. * if (err) return handleError(err);
  1937. * console.log('there are %d kittens', count);
  1938. * })
  1939. *
  1940. * @deprecated
  1941. * @param {Object} [filter] count documents that match this object
  1942. * @param {Function} [callback] optional params are (error, count)
  1943. * @return {Query} this
  1944. * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/
  1945. * @api public
  1946. */
  1947. Query.prototype.count = function(filter, callback) {
  1948. if (typeof filter === 'function') {
  1949. callback = filter;
  1950. filter = undefined;
  1951. }
  1952. filter = utils.toObject(filter);
  1953. if (mquery.canMerge(filter)) {
  1954. this.merge(filter);
  1955. }
  1956. this.op = 'count';
  1957. if (!callback) {
  1958. return this;
  1959. }
  1960. this._count(callback);
  1961. return this;
  1962. };
  1963. /**
  1964. * Specifies this query as a `estimatedDocumentCount()` query. Faster than
  1965. * using `countDocuments()` for large collections because
  1966. * `estimatedDocumentCount()` uses collection metadata rather than scanning
  1967. * the entire collection.
  1968. *
  1969. * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()`
  1970. * is equivalent to `Model.find().estimatedDocumentCount()`
  1971. *
  1972. * This function triggers the following middleware.
  1973. *
  1974. * - `estimatedDocumentCount()`
  1975. *
  1976. * ####Example:
  1977. *
  1978. * await Model.find().estimatedDocumentCount();
  1979. *
  1980. * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount)
  1981. * @param {Function} [callback] optional params are (error, count)
  1982. * @return {Query} this
  1983. * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount
  1984. * @api public
  1985. */
  1986. Query.prototype.estimatedDocumentCount = function(options, callback) {
  1987. if (typeof options === 'function') {
  1988. callback = options;
  1989. options = undefined;
  1990. }
  1991. if (typeof options === 'object' && options != null) {
  1992. this.setOptions(options);
  1993. }
  1994. this.op = 'estimatedDocumentCount';
  1995. if (!callback) {
  1996. return this;
  1997. }
  1998. this._estimatedDocumentCount(callback);
  1999. return this;
  2000. };
  2001. /**
  2002. * Specifies this query as a `countDocuments()` query. Behaves like `count()`,
  2003. * except it always does a full collection scan when passed an empty filter `{}`.
  2004. *
  2005. * There are also minor differences in how `countDocuments()` handles
  2006. * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
  2007. * versus `count()`.
  2008. *
  2009. * Passing a `callback` executes the query.
  2010. *
  2011. * This function triggers the following middleware.
  2012. *
  2013. * - `countDocuments()`
  2014. *
  2015. * ####Example:
  2016. *
  2017. * const countQuery = model.where({ 'color': 'black' }).countDocuments();
  2018. *
  2019. * query.countDocuments({ color: 'black' }).count(callback);
  2020. *
  2021. * query.countDocuments({ color: 'black' }, callback);
  2022. *
  2023. * query.where('color', 'black').countDocuments(function(err, count) {
  2024. * if (err) return handleError(err);
  2025. * console.log('there are %d kittens', count);
  2026. * });
  2027. *
  2028. * The `countDocuments()` function is similar to `count()`, but there are a
  2029. * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
  2030. * Below are the operators that `count()` supports but `countDocuments()` does not,
  2031. * and the suggested replacement:
  2032. *
  2033. * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/)
  2034. * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center)
  2035. * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)
  2036. *
  2037. * @param {Object} [filter] mongodb selector
  2038. * @param {Function} [callback] optional params are (error, count)
  2039. * @return {Query} this
  2040. * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments
  2041. * @api public
  2042. */
  2043. Query.prototype.countDocuments = function(conditions, callback) {
  2044. if (typeof conditions === 'function') {
  2045. callback = conditions;
  2046. conditions = undefined;
  2047. }
  2048. conditions = utils.toObject(conditions);
  2049. if (mquery.canMerge(conditions)) {
  2050. this.merge(conditions);
  2051. }
  2052. this.op = 'countDocuments';
  2053. if (!callback) {
  2054. return this;
  2055. }
  2056. this._countDocuments(callback);
  2057. return this;
  2058. };
  2059. /**
  2060. * Declares or executes a distict() operation.
  2061. *
  2062. * Passing a `callback` executes the query.
  2063. *
  2064. * This function does not trigger any middleware.
  2065. *
  2066. * ####Example
  2067. *
  2068. * distinct(field, conditions, callback)
  2069. * distinct(field, conditions)
  2070. * distinct(field, callback)
  2071. * distinct(field)
  2072. * distinct(callback)
  2073. * distinct()
  2074. *
  2075. * @param {String} [field]
  2076. * @param {Object|Query} [filter]
  2077. * @param {Function} [callback] optional params are (error, arr)
  2078. * @return {Query} this
  2079. * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/
  2080. * @api public
  2081. */
  2082. Query.prototype.distinct = function(field, conditions, callback) {
  2083. if (!callback) {
  2084. if (typeof conditions === 'function') {
  2085. callback = conditions;
  2086. conditions = undefined;
  2087. } else if (typeof field === 'function') {
  2088. callback = field;
  2089. field = undefined;
  2090. conditions = undefined;
  2091. }
  2092. }
  2093. conditions = utils.toObject(conditions);
  2094. if (mquery.canMerge(conditions)) {
  2095. this.merge(conditions);
  2096. prepareDiscriminatorCriteria(this);
  2097. } else if (conditions != null) {
  2098. this.error(new ObjectParameterError(conditions, 'filter', 'distinct'));
  2099. }
  2100. if (callback != null) {
  2101. this._castConditions();
  2102. if (this.error() != null) {
  2103. callback(this.error());
  2104. return this;
  2105. }
  2106. }
  2107. return Query.base.distinct.call(this, {}, field, callback);
  2108. };
  2109. /**
  2110. * Sets the sort order
  2111. *
  2112. * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.
  2113. *
  2114. * If a string is passed, it must be a space delimited list of path names. The
  2115. * sort order of each path is ascending unless the path name is prefixed with `-`
  2116. * which will be treated as descending.
  2117. *
  2118. * ####Example
  2119. *
  2120. * // sort by "field" ascending and "test" descending
  2121. * query.sort({ field: 'asc', test: -1 });
  2122. *
  2123. * // equivalent
  2124. * query.sort('field -test');
  2125. *
  2126. * ####Note
  2127. *
  2128. * Cannot be used with `distinct()`
  2129. *
  2130. * @param {Object|String} arg
  2131. * @return {Query} this
  2132. * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/
  2133. * @api public
  2134. */
  2135. Query.prototype.sort = function(arg) {
  2136. if (arguments.length > 1) {
  2137. throw new Error('sort() only takes 1 Argument');
  2138. }
  2139. return Query.base.sort.call(this, arg);
  2140. };
  2141. /**
  2142. * Declare and/or execute this query as a remove() operation.
  2143. *
  2144. * This function does not trigger any middleware
  2145. *
  2146. * ####Example
  2147. *
  2148. * Model.remove({ artist: 'Anne Murray' }, callback)
  2149. *
  2150. * ####Note
  2151. *
  2152. * The operation is only executed when a callback is passed. To force execution without a callback, you must first call `remove()` and then execute it by using the `exec()` method.
  2153. *
  2154. * // not executed
  2155. * var query = Model.find().remove({ name: 'Anne Murray' })
  2156. *
  2157. * // executed
  2158. * query.remove({ name: 'Anne Murray' }, callback)
  2159. * query.remove({ name: 'Anne Murray' }).remove(callback)
  2160. *
  2161. * // executed without a callback
  2162. * query.exec()
  2163. *
  2164. * // summary
  2165. * query.remove(conds, fn); // executes
  2166. * query.remove(conds)
  2167. * query.remove(fn) // executes
  2168. * query.remove()
  2169. *
  2170. * @param {Object|Query} [filter] mongodb selector
  2171. * @param {Function} [callback] optional params are (error, writeOpResult)
  2172. * @return {Query} this
  2173. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  2174. * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/
  2175. * @api public
  2176. */
  2177. Query.prototype.remove = function(filter, callback) {
  2178. if (typeof filter === 'function') {
  2179. callback = filter;
  2180. filter = null;
  2181. }
  2182. filter = utils.toObject(filter);
  2183. if (mquery.canMerge(filter)) {
  2184. this.merge(filter);
  2185. prepareDiscriminatorCriteria(this);
  2186. } else if (filter != null) {
  2187. this.error(new ObjectParameterError(filter, 'filter', 'remove'));
  2188. }
  2189. if (!callback) {
  2190. return Query.base.remove.call(this);
  2191. }
  2192. this._remove(callback);
  2193. return this;
  2194. };
  2195. /*!
  2196. * ignore
  2197. */
  2198. Query.prototype._remove = wrapThunk(function(callback) {
  2199. this._castConditions();
  2200. if (this.error() != null) {
  2201. callback(this.error());
  2202. return this;
  2203. }
  2204. callback = _wrapThunkCallback(this, callback);
  2205. return Query.base.remove.call(this, helpers.handleWriteOpResult(callback));
  2206. });
  2207. /**
  2208. * Declare and/or execute this query as a `deleteOne()` operation. Works like
  2209. * remove, except it deletes at most one document regardless of the `single`
  2210. * option.
  2211. *
  2212. * This function does not trigger any middleware.
  2213. *
  2214. * ####Example
  2215. *
  2216. * Character.deleteOne({ name: 'Eddard Stark' }, callback)
  2217. * Character.deleteOne({ name: 'Eddard Stark' }).then(next)
  2218. *
  2219. * @param {Object|Query} [filter] mongodb selector
  2220. * @param {Function} [callback] optional params are (error, writeOpResult)
  2221. * @return {Query} this
  2222. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  2223. * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/
  2224. * @api public
  2225. */
  2226. Query.prototype.deleteOne = function(filter, callback) {
  2227. if (typeof filter === 'function') {
  2228. callback = filter;
  2229. filter = null;
  2230. }
  2231. filter = utils.toObject(filter);
  2232. if (mquery.canMerge(filter)) {
  2233. this.merge(filter);
  2234. prepareDiscriminatorCriteria(this);
  2235. } else if (filter != null) {
  2236. this.error(new ObjectParameterError(filter, 'filter', 'deleteOne'));
  2237. }
  2238. if (!callback) {
  2239. return Query.base.deleteOne.call(this);
  2240. }
  2241. this._deleteOne.call(this, callback);
  2242. return this;
  2243. };
  2244. /*!
  2245. * Internal thunk for `deleteOne()`
  2246. */
  2247. Query.prototype._deleteOne = wrapThunk(function(callback) {
  2248. this._castConditions();
  2249. if (this.error() != null) {
  2250. callback(this.error());
  2251. return this;
  2252. }
  2253. callback = _wrapThunkCallback(this, callback);
  2254. return Query.base.deleteOne.call(this, helpers.handleWriteOpResult(callback));
  2255. });
  2256. /**
  2257. * Declare and/or execute this query as a `deleteMany()` operation. Works like
  2258. * remove, except it deletes _every_ document that matches `criteria` in the
  2259. * collection, regardless of the value of `single`.
  2260. *
  2261. * This function does not trigger any middleware
  2262. *
  2263. * ####Example
  2264. *
  2265. * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback)
  2266. * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next)
  2267. *
  2268. * @param {Object|Query} [filter] mongodb selector
  2269. * @param {Function} [callback] optional params are (error, writeOpResult)
  2270. * @return {Query} this
  2271. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  2272. * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/
  2273. * @api public
  2274. */
  2275. Query.prototype.deleteMany = function(filter, callback) {
  2276. if (typeof filter === 'function') {
  2277. callback = filter;
  2278. filter = null;
  2279. }
  2280. filter = utils.toObject(filter);
  2281. if (mquery.canMerge(filter)) {
  2282. this.merge(filter);
  2283. prepareDiscriminatorCriteria(this);
  2284. } else if (filter != null) {
  2285. this.error(new ObjectParameterError(filter, 'filter', 'deleteMany'));
  2286. }
  2287. if (!callback) {
  2288. return Query.base.deleteMany.call(this);
  2289. }
  2290. this._deleteMany.call(this, callback);
  2291. return this;
  2292. };
  2293. /*!
  2294. * Internal thunk around `deleteMany()`
  2295. */
  2296. Query.prototype._deleteMany = wrapThunk(function(callback) {
  2297. this._castConditions();
  2298. if (this.error() != null) {
  2299. callback(this.error());
  2300. return this;
  2301. }
  2302. callback = _wrapThunkCallback(this, callback);
  2303. return Query.base.deleteMany.call(this, helpers.handleWriteOpResult(callback));
  2304. });
  2305. /*!
  2306. * hydrates a document
  2307. *
  2308. * @param {Model} model
  2309. * @param {Document} doc
  2310. * @param {Object} res 3rd parameter to callback
  2311. * @param {Object} fields
  2312. * @param {Query} self
  2313. * @param {Array} [pop] array of paths used in population
  2314. * @param {Function} callback
  2315. */
  2316. function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) {
  2317. const opts = pop ?
  2318. {populated: pop}
  2319. : undefined;
  2320. const casted = helpers.createModel(model, doc, fields, userProvidedFields);
  2321. try {
  2322. casted.init(doc, opts, _init);
  2323. } catch (error) {
  2324. _init(error);
  2325. }
  2326. function _init(err) {
  2327. if (err) {
  2328. return process.nextTick(() => callback(err));
  2329. }
  2330. casted.$session(options.session);
  2331. if (options.rawResult) {
  2332. res.value = casted;
  2333. return process.nextTick(() => callback(null, res));
  2334. }
  2335. process.nextTick(() => callback(null, casted));
  2336. }
  2337. }
  2338. /*!
  2339. * If the model is a discriminator type and not root, then add the key & value to the criteria.
  2340. */
  2341. function prepareDiscriminatorCriteria(query) {
  2342. if (!query || !query.model || !query.model.schema) {
  2343. return;
  2344. }
  2345. const schema = query.model.schema;
  2346. if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
  2347. query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
  2348. }
  2349. }
  2350. /**
  2351. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
  2352. *
  2353. * 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.
  2354. *
  2355. * This function triggers the following middleware.
  2356. *
  2357. * - `findOneAndUpdate()`
  2358. *
  2359. * ####Available options
  2360. *
  2361. * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  2362. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  2363. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
  2364. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2365. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2366. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  2367. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
  2368. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2369. * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
  2370. *
  2371. * ####Callback Signature
  2372. * function(error, doc) {
  2373. * // error: any errors that occurred
  2374. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2375. * }
  2376. *
  2377. * ####Examples
  2378. *
  2379. * query.findOneAndUpdate(conditions, update, options, callback) // executes
  2380. * query.findOneAndUpdate(conditions, update, options) // returns Query
  2381. * query.findOneAndUpdate(conditions, update, callback) // executes
  2382. * query.findOneAndUpdate(conditions, update) // returns Query
  2383. * query.findOneAndUpdate(update, callback) // returns Query
  2384. * query.findOneAndUpdate(update) // returns Query
  2385. * query.findOneAndUpdate(callback) // executes
  2386. * query.findOneAndUpdate() // returns Query
  2387. *
  2388. * @method findOneAndUpdate
  2389. * @memberOf Query
  2390. * @instance
  2391. * @param {Object|Query} [query]
  2392. * @param {Object} [doc]
  2393. * @param {Object} [options]
  2394. * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2395. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2396. * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
  2397. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean).
  2398. * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult)
  2399. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2400. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  2401. * @return {Query} this
  2402. * @api public
  2403. */
  2404. Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
  2405. this.op = 'findOneAndUpdate';
  2406. this._validate();
  2407. switch (arguments.length) {
  2408. case 3:
  2409. if (typeof options === 'function') {
  2410. callback = options;
  2411. options = {};
  2412. }
  2413. break;
  2414. case 2:
  2415. if (typeof doc === 'function') {
  2416. callback = doc;
  2417. doc = criteria;
  2418. criteria = undefined;
  2419. }
  2420. options = undefined;
  2421. break;
  2422. case 1:
  2423. if (typeof criteria === 'function') {
  2424. callback = criteria;
  2425. criteria = options = doc = undefined;
  2426. } else {
  2427. doc = criteria;
  2428. criteria = options = undefined;
  2429. }
  2430. }
  2431. if (mquery.canMerge(criteria)) {
  2432. this.merge(criteria);
  2433. }
  2434. // apply doc
  2435. if (doc) {
  2436. this._mergeUpdate(doc);
  2437. }
  2438. if (options) {
  2439. options = utils.clone(options);
  2440. if (options.projection) {
  2441. this.select(options.projection);
  2442. delete options.projection;
  2443. }
  2444. if (options.fields) {
  2445. this.select(options.fields);
  2446. delete options.fields;
  2447. }
  2448. this.setOptions(options);
  2449. }
  2450. if (!callback) {
  2451. return this;
  2452. }
  2453. this._findOneAndUpdate(callback);
  2454. return this;
  2455. };
  2456. /*!
  2457. * Thunk around findOneAndUpdate()
  2458. *
  2459. * @param {Function} [callback]
  2460. * @api private
  2461. */
  2462. Query.prototype._findOneAndUpdate = wrapThunk(function(callback) {
  2463. if (this.error() != null) {
  2464. return callback(this.error());
  2465. }
  2466. this._findAndModify('update', callback);
  2467. });
  2468. /**
  2469. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
  2470. *
  2471. * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed.
  2472. *
  2473. * This function triggers the following middleware.
  2474. *
  2475. * - `findOneAndRemove()`
  2476. *
  2477. * ####Available options
  2478. *
  2479. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2480. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2481. * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2482. *
  2483. * ####Callback Signature
  2484. * function(error, doc) {
  2485. * // error: any errors that occurred
  2486. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2487. * }
  2488. *
  2489. * ####Examples
  2490. *
  2491. * A.where().findOneAndRemove(conditions, options, callback) // executes
  2492. * A.where().findOneAndRemove(conditions, options) // return Query
  2493. * A.where().findOneAndRemove(conditions, callback) // executes
  2494. * A.where().findOneAndRemove(conditions) // returns Query
  2495. * A.where().findOneAndRemove(callback) // executes
  2496. * A.where().findOneAndRemove() // returns Query
  2497. *
  2498. * @method findOneAndRemove
  2499. * @memberOf Query
  2500. * @instance
  2501. * @param {Object} [conditions]
  2502. * @param {Object} [options]
  2503. * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2504. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2505. * @param {Function} [callback] optional params are (error, document)
  2506. * @return {Query} this
  2507. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2508. * @api public
  2509. */
  2510. Query.prototype.findOneAndRemove = function(conditions, options, callback) {
  2511. this.op = 'findOneAndRemove';
  2512. this._validate();
  2513. switch (arguments.length) {
  2514. case 2:
  2515. if (typeof options === 'function') {
  2516. callback = options;
  2517. options = {};
  2518. }
  2519. break;
  2520. case 1:
  2521. if (typeof conditions === 'function') {
  2522. callback = conditions;
  2523. conditions = undefined;
  2524. options = undefined;
  2525. }
  2526. break;
  2527. }
  2528. if (mquery.canMerge(conditions)) {
  2529. this.merge(conditions);
  2530. }
  2531. options && this.setOptions(options);
  2532. if (!callback) {
  2533. return this;
  2534. }
  2535. this._findOneAndRemove(callback);
  2536. return this;
  2537. };
  2538. /**
  2539. * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command.
  2540. *
  2541. * Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes immediately if `callback` is passed.
  2542. *
  2543. * This function triggers the following middleware.
  2544. *
  2545. * - `findOneAndDelete()`
  2546. *
  2547. * This function differs slightly from `Model.findOneAndRemove()` in that
  2548. * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/),
  2549. * as opposed to a `findOneAndDelete()` command. For most mongoose use cases,
  2550. * this distinction is purely pedantic. You should use `findOneAndDelete()`
  2551. * unless you have a good reason not to.
  2552. *
  2553. * ####Available options
  2554. *
  2555. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2556. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2557. * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2558. *
  2559. * ####Callback Signature
  2560. * function(error, doc) {
  2561. * // error: any errors that occurred
  2562. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2563. * }
  2564. *
  2565. * ####Examples
  2566. *
  2567. * A.where().findOneAndDelete(conditions, options, callback) // executes
  2568. * A.where().findOneAndDelete(conditions, options) // return Query
  2569. * A.where().findOneAndDelete(conditions, callback) // executes
  2570. * A.where().findOneAndDelete(conditions) // returns Query
  2571. * A.where().findOneAndDelete(callback) // executes
  2572. * A.where().findOneAndDelete() // returns Query
  2573. *
  2574. * @method findOneAndDelete
  2575. * @memberOf Query
  2576. * @param {Object} [conditions]
  2577. * @param {Object} [options]
  2578. * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2579. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2580. * @param {Function} [callback] optional params are (error, document)
  2581. * @return {Query} this
  2582. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2583. * @api public
  2584. */
  2585. Query.prototype.findOneAndDelete = function(conditions, options, callback) {
  2586. this.op = 'findOneAndDelete';
  2587. this._validate();
  2588. switch (arguments.length) {
  2589. case 2:
  2590. if (typeof options === 'function') {
  2591. callback = options;
  2592. options = {};
  2593. }
  2594. break;
  2595. case 1:
  2596. if (typeof conditions === 'function') {
  2597. callback = conditions;
  2598. conditions = undefined;
  2599. options = undefined;
  2600. }
  2601. break;
  2602. }
  2603. if (mquery.canMerge(conditions)) {
  2604. this.merge(conditions);
  2605. }
  2606. options && this.setOptions(options);
  2607. if (!callback) {
  2608. return this;
  2609. }
  2610. this._findOneAndDelete(callback);
  2611. return this;
  2612. };
  2613. /*!
  2614. * Thunk around findOneAndDelete()
  2615. *
  2616. * @param {Function} [callback]
  2617. * @return {Query} this
  2618. * @api private
  2619. */
  2620. Query.prototype._findOneAndDelete = wrapThunk(function(callback) {
  2621. this._castConditions();
  2622. if (this.error() != null) {
  2623. callback(this.error());
  2624. return null;
  2625. }
  2626. const filter = this._conditions;
  2627. const options = this._optionsForExec();
  2628. let fields = null;
  2629. if (this._fields != null) {
  2630. options.projection = this._castFields(utils.clone(this._fields));
  2631. fields = options.projection;
  2632. if (fields instanceof Error) {
  2633. callback(fields);
  2634. return null;
  2635. }
  2636. }
  2637. this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => {
  2638. if (err) {
  2639. return callback(err);
  2640. }
  2641. const doc = res.value;
  2642. return this._completeOne(doc, res, callback);
  2643. }));
  2644. });
  2645. /**
  2646. * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command.
  2647. *
  2648. * Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes immediately if `callback` is passed.
  2649. *
  2650. * This function triggers the following middleware.
  2651. *
  2652. * - `findOneAndReplace()`
  2653. *
  2654. * ####Available options
  2655. *
  2656. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2657. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2658. * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2659. *
  2660. * ####Callback Signature
  2661. * function(error, doc) {
  2662. * // error: any errors that occurred
  2663. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2664. * }
  2665. *
  2666. * ####Examples
  2667. *
  2668. * A.where().findOneAndReplace(conditions, options, callback) // executes
  2669. * A.where().findOneAndReplace(conditions, options) // return Query
  2670. * A.where().findOneAndReplace(conditions, callback) // executes
  2671. * A.where().findOneAndReplace(conditions) // returns Query
  2672. * A.where().findOneAndReplace(callback) // executes
  2673. * A.where().findOneAndReplace() // returns Query
  2674. *
  2675. * @method findOneAndReplace
  2676. * @memberOf Query
  2677. * @param {Object} [conditions]
  2678. * @param {Object} [options]
  2679. * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2680. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2681. * @param {Function} [callback] optional params are (error, document)
  2682. * @return {Query} this
  2683. * @api public
  2684. */
  2685. Query.prototype.findOneAndReplace = function(conditions, options, callback) {
  2686. this.op = 'findOneAndReplace';
  2687. this._validate();
  2688. switch (arguments.length) {
  2689. case 2:
  2690. if (typeof options === 'function') {
  2691. callback = options;
  2692. options = {};
  2693. }
  2694. break;
  2695. case 1:
  2696. if (typeof conditions === 'function') {
  2697. callback = conditions;
  2698. conditions = undefined;
  2699. options = undefined;
  2700. }
  2701. break;
  2702. }
  2703. if (mquery.canMerge(conditions)) {
  2704. this.merge(conditions);
  2705. }
  2706. options && this.setOptions(options);
  2707. if (!callback) {
  2708. return this;
  2709. }
  2710. this._findOneAndReplace(callback);
  2711. return this;
  2712. };
  2713. /*!
  2714. * Thunk around findOneAndReplace()
  2715. *
  2716. * @param {Function} [callback]
  2717. * @return {Query} this
  2718. * @api private
  2719. */
  2720. Query.prototype._findOneAndReplace = wrapThunk(function(callback) {
  2721. this._castConditions();
  2722. if (this.error() != null) {
  2723. callback(this.error());
  2724. return null;
  2725. }
  2726. const filter = this._conditions;
  2727. const options = this._optionsForExec();
  2728. let fields = null;
  2729. if (this._fields != null) {
  2730. options.projection = this._castFields(utils.clone(this._fields));
  2731. fields = options.projection;
  2732. if (fields instanceof Error) {
  2733. callback(fields);
  2734. return null;
  2735. }
  2736. }
  2737. this._collection.collection.findOneAndReplace(filter, options, (err, res) => {
  2738. if (err) {
  2739. return callback(err);
  2740. }
  2741. const doc = res.value;
  2742. return this._completeOne(doc, res, callback);
  2743. });
  2744. });
  2745. /*!
  2746. * Thunk around findOneAndRemove()
  2747. *
  2748. * @param {Function} [callback]
  2749. * @return {Query} this
  2750. * @api private
  2751. */
  2752. Query.prototype._findOneAndRemove = wrapThunk(function(callback) {
  2753. if (this.error() != null) {
  2754. callback(this.error());
  2755. return;
  2756. }
  2757. this._findAndModify('remove', callback);
  2758. });
  2759. /*!
  2760. * Get options from query opts, falling back to the base mongoose object.
  2761. */
  2762. function _getOption(query, option, def) {
  2763. const opts = query._optionsForExec(query.model);
  2764. if (option in opts) {
  2765. return opts[option];
  2766. }
  2767. if (option in query.model.base.options) {
  2768. return query.model.base.options[option];
  2769. }
  2770. return def;
  2771. }
  2772. /*!
  2773. * Override mquery.prototype._findAndModify to provide casting etc.
  2774. *
  2775. * @param {String} type - either "remove" or "update"
  2776. * @param {Function} callback
  2777. * @api private
  2778. */
  2779. Query.prototype._findAndModify = function(type, callback) {
  2780. if (typeof callback !== 'function') {
  2781. throw new Error('Expected callback in _findAndModify');
  2782. }
  2783. const model = this.model;
  2784. const schema = model.schema;
  2785. const _this = this;
  2786. let castedDoc = this._update;
  2787. let fields;
  2788. let doValidate;
  2789. const castedQuery = castQuery(this);
  2790. if (castedQuery instanceof Error) {
  2791. return callback(castedQuery);
  2792. }
  2793. const opts = this._optionsForExec(model);
  2794. if ('strict' in opts) {
  2795. this._mongooseOptions.strict = opts.strict;
  2796. }
  2797. const isOverwriting = this.options.overwrite && !hasDollarKeys(castedDoc);
  2798. if (isOverwriting) {
  2799. castedDoc = new this.model(castedDoc, null, true);
  2800. }
  2801. if (type === 'remove') {
  2802. opts.remove = true;
  2803. } else {
  2804. if (!('new' in opts)) {
  2805. opts.new = false;
  2806. }
  2807. if (!('upsert' in opts)) {
  2808. opts.upsert = false;
  2809. }
  2810. if (opts.upsert || opts['new']) {
  2811. opts.remove = false;
  2812. }
  2813. if (isOverwriting) {
  2814. doValidate = function(callback) {
  2815. castedDoc.validate(callback);
  2816. };
  2817. } else {
  2818. castedDoc = castDoc(this, opts.overwrite);
  2819. castedDoc = setDefaultsOnInsert(this._conditions, schema, castedDoc, opts);
  2820. if (!castedDoc) {
  2821. if (opts.upsert) {
  2822. // still need to do the upsert to empty doc
  2823. const doc = utils.clone(castedQuery);
  2824. delete doc._id;
  2825. castedDoc = {$set: doc};
  2826. } else {
  2827. this.findOne(callback);
  2828. return this;
  2829. }
  2830. } else if (castedDoc instanceof Error) {
  2831. return callback(castedDoc);
  2832. } else {
  2833. // In order to make MongoDB 2.6 happy (see
  2834. // https://jira.mongodb.org/browse/SERVER-12266 and related issues)
  2835. // if we have an actual update document but $set is empty, junk the $set.
  2836. if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) {
  2837. delete castedDoc.$set;
  2838. }
  2839. }
  2840. doValidate = updateValidators(this, schema, castedDoc, opts);
  2841. }
  2842. }
  2843. this._applyPaths();
  2844. const options = this._mongooseOptions;
  2845. if (this._fields) {
  2846. fields = utils.clone(this._fields);
  2847. opts.projection = this._castFields(fields);
  2848. if (opts.projection instanceof Error) {
  2849. return callback(opts.projection);
  2850. }
  2851. }
  2852. if (opts.sort) convertSortToArray(opts);
  2853. const cb = function(err, doc, res) {
  2854. if (err) {
  2855. return callback(err);
  2856. }
  2857. _this._completeOne(doc, res, callback);
  2858. };
  2859. let _callback;
  2860. let useFindAndModify = true;
  2861. const runValidators = _getOption(this, 'runValidators', false);
  2862. const base = _this.model && _this.model.base;
  2863. const conn = get(model, 'collection.conn', {});
  2864. if ('useFindAndModify' in base.options) {
  2865. useFindAndModify = base.get('useFindAndModify');
  2866. }
  2867. if ('useFindAndModify' in conn.config) {
  2868. useFindAndModify = conn.config.useFindAndModify;
  2869. }
  2870. if ('useFindAndModify' in options) {
  2871. useFindAndModify = options.useFindAndModify;
  2872. }
  2873. if (useFindAndModify === false) {
  2874. // Bypass mquery
  2875. const collection = _this._collection.collection;
  2876. if ('new' in opts) {
  2877. opts.returnOriginal = !opts['new'];
  2878. delete opts['new'];
  2879. }
  2880. if (type === 'remove') {
  2881. collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) {
  2882. return cb(error, res ? res.value : res, res);
  2883. }));
  2884. return this;
  2885. }
  2886. // honors legacy overwrite option for backward compatibility
  2887. const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate';
  2888. if (runValidators && doValidate) {
  2889. _callback = function(error) {
  2890. if (error) {
  2891. return callback(error);
  2892. }
  2893. if (castedDoc && castedDoc.toBSON) {
  2894. castedDoc = castedDoc.toBSON();
  2895. }
  2896. collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
  2897. return cb(error, res ? res.value : res, res);
  2898. }));
  2899. };
  2900. try {
  2901. doValidate(_callback);
  2902. } catch (error) {
  2903. callback(error);
  2904. }
  2905. } else {
  2906. if (castedDoc && castedDoc.toBSON) {
  2907. castedDoc = castedDoc.toBSON();
  2908. }
  2909. collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
  2910. return cb(error, res ? res.value : res, res);
  2911. }));
  2912. }
  2913. return this;
  2914. }
  2915. if (runValidators && doValidate) {
  2916. _callback = function(error) {
  2917. if (error) {
  2918. return callback(error);
  2919. }
  2920. if (castedDoc && castedDoc.toBSON) {
  2921. castedDoc = castedDoc.toBSON();
  2922. }
  2923. _this._collection.findAndModify(castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
  2924. return cb(error, res ? res.value : res, res);
  2925. }));
  2926. };
  2927. try {
  2928. doValidate(_callback);
  2929. } catch (error) {
  2930. callback(error);
  2931. }
  2932. } else {
  2933. if (castedDoc && castedDoc.toBSON) {
  2934. castedDoc = castedDoc.toBSON();
  2935. }
  2936. this._collection.findAndModify(castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
  2937. return cb(error, res ? res.value : res, res);
  2938. }));
  2939. }
  2940. return this;
  2941. };
  2942. /*!
  2943. * ignore
  2944. */
  2945. function _completeOneLean(doc, res, opts, callback) {
  2946. if (opts.rawResult) {
  2947. return callback(null, res);
  2948. }
  2949. return callback(null, doc);
  2950. }
  2951. /*!
  2952. * Override mquery.prototype._mergeUpdate to handle mongoose objects in
  2953. * updates.
  2954. *
  2955. * @param {Object} doc
  2956. * @api private
  2957. */
  2958. Query.prototype._mergeUpdate = function(doc) {
  2959. if (!this._update) this._update = {};
  2960. if (doc instanceof Query) {
  2961. if (doc._update) {
  2962. utils.mergeClone(this._update, doc._update);
  2963. }
  2964. } else {
  2965. utils.mergeClone(this._update, doc);
  2966. }
  2967. };
  2968. /*!
  2969. * The mongodb driver 1.3.23 only supports the nested array sort
  2970. * syntax. We must convert it or sorting findAndModify will not work.
  2971. */
  2972. function convertSortToArray(opts) {
  2973. if (Array.isArray(opts.sort)) {
  2974. return;
  2975. }
  2976. if (!utils.isObject(opts.sort)) {
  2977. return;
  2978. }
  2979. const sort = [];
  2980. for (const key in opts.sort) {
  2981. if (utils.object.hasOwnProperty(opts.sort, key)) {
  2982. sort.push([key, opts.sort[key]]);
  2983. }
  2984. }
  2985. opts.sort = sort;
  2986. }
  2987. /*!
  2988. * ignore
  2989. */
  2990. function _updateThunk(op, callback) {
  2991. const schema = this.model.schema;
  2992. let doValidate;
  2993. const _this = this;
  2994. this._castConditions();
  2995. if (this.error() != null) {
  2996. callback(this.error());
  2997. return null;
  2998. }
  2999. callback = _wrapThunkCallback(this, callback);
  3000. const castedQuery = this._conditions;
  3001. let castedDoc;
  3002. const options = this._optionsForExec(this.model);
  3003. ++this._executionCount;
  3004. this._update = utils.clone(this._update, options);
  3005. const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update);
  3006. if (isOverwriting) {
  3007. castedDoc = new this.model(this._update, null, true);
  3008. } else {
  3009. castedDoc = castDoc(this, options.overwrite);
  3010. if (castedDoc instanceof Error) {
  3011. callback(castedDoc);
  3012. return null;
  3013. }
  3014. if (castedDoc == null || Object.keys(castedDoc).length === 0) {
  3015. callback(null, 0);
  3016. return null;
  3017. }
  3018. castedDoc = setDefaultsOnInsert(this._conditions, this.model.schema,
  3019. castedDoc, options);
  3020. }
  3021. const runValidators = _getOption(this, 'runValidators', false);
  3022. if (runValidators) {
  3023. if (isOverwriting) {
  3024. doValidate = function(callback) {
  3025. castedDoc.validate(callback);
  3026. };
  3027. } else {
  3028. doValidate = updateValidators(this, schema, castedDoc, options);
  3029. }
  3030. const _callback = function(err) {
  3031. if (err) {
  3032. return callback(err);
  3033. }
  3034. if (castedDoc.toBSON) {
  3035. castedDoc = castedDoc.toBSON();
  3036. }
  3037. _this._collection[op](castedQuery, castedDoc, options, callback);
  3038. };
  3039. try {
  3040. doValidate(_callback);
  3041. } catch (err) {
  3042. process.nextTick(function() {
  3043. callback(err);
  3044. });
  3045. }
  3046. return null;
  3047. }
  3048. if (castedDoc.toBSON) {
  3049. castedDoc = castedDoc.toBSON();
  3050. }
  3051. this._collection[op](castedQuery, castedDoc, options, callback);
  3052. return null;
  3053. }
  3054. /*!
  3055. * Internal thunk for .update()
  3056. *
  3057. * @param {Function} callback
  3058. * @see Model.update #model_Model.update
  3059. * @api private
  3060. */
  3061. Query.prototype._execUpdate = wrapThunk(function(callback) {
  3062. return _updateThunk.call(this, 'update', callback);
  3063. });
  3064. /*!
  3065. * Internal thunk for .updateMany()
  3066. *
  3067. * @param {Function} callback
  3068. * @see Model.update #model_Model.update
  3069. * @api private
  3070. */
  3071. Query.prototype._updateMany = wrapThunk(function(callback) {
  3072. return _updateThunk.call(this, 'updateMany', callback);
  3073. });
  3074. /*!
  3075. * Internal thunk for .updateOne()
  3076. *
  3077. * @param {Function} callback
  3078. * @see Model.update #model_Model.update
  3079. * @api private
  3080. */
  3081. Query.prototype._updateOne = wrapThunk(function(callback) {
  3082. return _updateThunk.call(this, 'updateOne', callback);
  3083. });
  3084. /*!
  3085. * Internal thunk for .replaceOne()
  3086. *
  3087. * @param {Function} callback
  3088. * @see Model.replaceOne #model_Model.replaceOne
  3089. * @api private
  3090. */
  3091. Query.prototype._replaceOne = wrapThunk(function(callback) {
  3092. return _updateThunk.call(this, 'replaceOne', callback);
  3093. });
  3094. /**
  3095. * Declare and/or execute this query as an update() operation.
  3096. *
  3097. * _All paths passed that are not $atomic operations will become $set ops._
  3098. *
  3099. * This function triggers the following middleware.
  3100. *
  3101. * - `update()`
  3102. *
  3103. * ####Example
  3104. *
  3105. * Model.where({ _id: id }).update({ title: 'words' })
  3106. *
  3107. * // becomes
  3108. *
  3109. * Model.where({ _id: id }).update({ $set: { title: 'words' }})
  3110. *
  3111. * ####Valid options:
  3112. *
  3113. * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
  3114. * - `multi` (boolean) whether multiple documents should be updated (false)
  3115. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  3116. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
  3117. * - `strict` (boolean) overrides the `strict` option for this update
  3118. * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
  3119. * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false.
  3120. * - `read`
  3121. * - `writeConcern`
  3122. *
  3123. * ####Note
  3124. *
  3125. * 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.
  3126. *
  3127. * ####Note
  3128. *
  3129. * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method.
  3130. *
  3131. * var q = Model.where({ _id: id });
  3132. * q.update({ $set: { name: 'bob' }}).update(); // not executed
  3133. *
  3134. * q.update({ $set: { name: 'bob' }}).exec(); // executed
  3135. *
  3136. * // keys that are not $atomic ops become $set.
  3137. * // this executes the same command as the previous example.
  3138. * q.update({ name: 'bob' }).exec();
  3139. *
  3140. * // overwriting with empty docs
  3141. * var q = Model.where({ _id: id }).setOptions({ overwrite: true })
  3142. * q.update({ }, callback); // executes
  3143. *
  3144. * // multi update with overwrite to empty doc
  3145. * var q = Model.where({ _id: id });
  3146. * q.setOptions({ multi: true, overwrite: true })
  3147. * q.update({ });
  3148. * q.update(callback); // executed
  3149. *
  3150. * // multi updates
  3151. * Model.where()
  3152. * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
  3153. *
  3154. * // more multi updates
  3155. * Model.where()
  3156. * .setOptions({ multi: true })
  3157. * .update({ $set: { arr: [] }}, callback)
  3158. *
  3159. * // single update by default
  3160. * Model.where({ email: 'address@example.com' })
  3161. * .update({ $inc: { counter: 1 }}, callback)
  3162. *
  3163. * API summary
  3164. *
  3165. * update(criteria, doc, options, cb) // executes
  3166. * update(criteria, doc, options)
  3167. * update(criteria, doc, cb) // executes
  3168. * update(criteria, doc)
  3169. * update(doc, cb) // executes
  3170. * update(doc)
  3171. * update(cb) // executes
  3172. * update(true) // executes
  3173. * update()
  3174. *
  3175. * @param {Object} [criteria]
  3176. * @param {Object} [doc] the update command
  3177. * @param {Object} [options]
  3178. * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
  3179. * @param {Function} [callback] optional, params are (error, writeOpResult)
  3180. * @return {Query} this
  3181. * @see Model.update #model_Model.update
  3182. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3183. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3184. * @api public
  3185. */
  3186. Query.prototype.update = function(conditions, doc, options, callback) {
  3187. if (typeof options === 'function') {
  3188. // .update(conditions, doc, callback)
  3189. callback = options;
  3190. options = null;
  3191. } else if (typeof doc === 'function') {
  3192. // .update(doc, callback);
  3193. callback = doc;
  3194. doc = conditions;
  3195. conditions = {};
  3196. options = null;
  3197. } else if (typeof conditions === 'function') {
  3198. // .update(callback)
  3199. callback = conditions;
  3200. conditions = undefined;
  3201. doc = undefined;
  3202. options = undefined;
  3203. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3204. // .update(doc)
  3205. doc = conditions;
  3206. conditions = undefined;
  3207. options = undefined;
  3208. callback = undefined;
  3209. }
  3210. return _update(this, 'update', conditions, doc, options, callback);
  3211. };
  3212. /**
  3213. * Declare and/or execute this query as an updateMany() operation. Same as
  3214. * `update()`, except MongoDB will update _all_ documents that match
  3215. * `criteria` (as opposed to just the first one) regardless of the value of
  3216. * the `multi` option.
  3217. *
  3218. * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
  3219. * and `post('updateMany')` instead.
  3220. *
  3221. * This function triggers the following middleware.
  3222. *
  3223. * - `updateMany()`
  3224. *
  3225. * @param {Object} [criteria]
  3226. * @param {Object} [doc] the update command
  3227. * @param {Object} [options]
  3228. @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
  3229. * @param {Function} [callback] optional params are (error, writeOpResult)
  3230. * @return {Query} this
  3231. * @see Model.update #model_Model.update
  3232. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3233. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3234. * @api public
  3235. */
  3236. Query.prototype.updateMany = function(conditions, doc, options, callback) {
  3237. if (typeof options === 'function') {
  3238. // .update(conditions, doc, callback)
  3239. callback = options;
  3240. options = null;
  3241. } else if (typeof doc === 'function') {
  3242. // .update(doc, callback);
  3243. callback = doc;
  3244. doc = conditions;
  3245. conditions = {};
  3246. options = null;
  3247. } else if (typeof conditions === 'function') {
  3248. // .update(callback)
  3249. callback = conditions;
  3250. conditions = undefined;
  3251. doc = undefined;
  3252. options = undefined;
  3253. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3254. // .update(doc)
  3255. doc = conditions;
  3256. conditions = undefined;
  3257. options = undefined;
  3258. callback = undefined;
  3259. }
  3260. return _update(this, 'updateMany', conditions, doc, options, callback);
  3261. };
  3262. /**
  3263. * Declare and/or execute this query as an updateOne() operation. Same as
  3264. * `update()`, except it does not support the `multi` or `overwrite` options.
  3265. *
  3266. * - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option.
  3267. * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`.
  3268. *
  3269. * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')`
  3270. * and `post('updateOne')` instead.
  3271. *
  3272. * This function triggers the following middleware.
  3273. *
  3274. * - `updateOne()`
  3275. *
  3276. * @param {Object} [criteria]
  3277. * @param {Object} [doc] the update command
  3278. * @param {Object} [options]
  3279. @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
  3280. * @param {Function} [callback] params are (error, writeOpResult)
  3281. * @return {Query} this
  3282. * @see Model.update #model_Model.update
  3283. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3284. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3285. * @api public
  3286. */
  3287. Query.prototype.updateOne = function(conditions, doc, options, callback) {
  3288. if (typeof options === 'function') {
  3289. // .update(conditions, doc, callback)
  3290. callback = options;
  3291. options = null;
  3292. } else if (typeof doc === 'function') {
  3293. // .update(doc, callback);
  3294. callback = doc;
  3295. doc = conditions;
  3296. conditions = {};
  3297. options = null;
  3298. } else if (typeof conditions === 'function') {
  3299. // .update(callback)
  3300. callback = conditions;
  3301. conditions = undefined;
  3302. doc = undefined;
  3303. options = undefined;
  3304. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3305. // .update(doc)
  3306. doc = conditions;
  3307. conditions = undefined;
  3308. options = undefined;
  3309. callback = undefined;
  3310. }
  3311. return _update(this, 'updateOne', conditions, doc, options, callback);
  3312. };
  3313. /**
  3314. * Declare and/or execute this query as a replaceOne() operation. Same as
  3315. * `update()`, except MongoDB will replace the existing document and will
  3316. * not accept any atomic operators (`$set`, etc.)
  3317. *
  3318. * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')`
  3319. * and `post('replaceOne')` instead.
  3320. *
  3321. * This function triggers the following middleware.
  3322. *
  3323. * - `replaceOne()`
  3324. *
  3325. * @param {Object} [criteria]
  3326. * @param {Object} [doc] the update command
  3327. * @param {Object} [options]
  3328. * @param {Function} [callback] optional params are (error, writeOpResult)
  3329. * @return {Query} this
  3330. * @see Model.update #model_Model.update
  3331. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3332. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3333. * @api public
  3334. */
  3335. Query.prototype.replaceOne = function(conditions, doc, options, callback) {
  3336. if (typeof options === 'function') {
  3337. // .update(conditions, doc, callback)
  3338. callback = options;
  3339. options = null;
  3340. } else if (typeof doc === 'function') {
  3341. // .update(doc, callback);
  3342. callback = doc;
  3343. doc = conditions;
  3344. conditions = {};
  3345. options = null;
  3346. } else if (typeof conditions === 'function') {
  3347. // .update(callback)
  3348. callback = conditions;
  3349. conditions = undefined;
  3350. doc = undefined;
  3351. options = undefined;
  3352. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3353. // .update(doc)
  3354. doc = conditions;
  3355. conditions = undefined;
  3356. options = undefined;
  3357. callback = undefined;
  3358. }
  3359. this.setOptions({ overwrite: true });
  3360. return _update(this, 'replaceOne', conditions, doc, options, callback);
  3361. };
  3362. /*!
  3363. * Internal helper for update, updateMany, updateOne, replaceOne
  3364. */
  3365. function _update(query, op, filter, doc, options, callback) {
  3366. // make sure we don't send in the whole Document to merge()
  3367. query.op = op;
  3368. filter = utils.toObject(filter);
  3369. doc = doc || {};
  3370. const oldCb = callback;
  3371. if (oldCb) {
  3372. if (typeof oldCb === 'function') {
  3373. callback = function(error, result) {
  3374. oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0});
  3375. };
  3376. } else {
  3377. throw new Error('Invalid callback() argument.');
  3378. }
  3379. }
  3380. // strict is an option used in the update checking, make sure it gets set
  3381. if (options) {
  3382. if ('strict' in options) {
  3383. query._mongooseOptions.strict = options.strict;
  3384. }
  3385. }
  3386. if (!(filter instanceof Query) &&
  3387. filter != null &&
  3388. filter.toString() !== '[object Object]') {
  3389. query.error(new ObjectParameterError(filter, 'filter', op));
  3390. } else {
  3391. query.merge(filter);
  3392. }
  3393. if (utils.isObject(options)) {
  3394. query.setOptions(options);
  3395. }
  3396. query._mergeUpdate(doc);
  3397. // Hooks
  3398. if (callback) {
  3399. if (op === 'update') {
  3400. query._execUpdate(callback);
  3401. return query;
  3402. }
  3403. query['_' + op](callback);
  3404. return query;
  3405. }
  3406. return Query.base[op].call(query, filter, doc, options, callback);
  3407. }
  3408. /**
  3409. * Runs a function `fn` and treats the return value of `fn` as the new value
  3410. * for the query to resolve to.
  3411. *
  3412. * Any functions you pass to `map()` will run **after** any post hooks.
  3413. *
  3414. * ####Example:
  3415. *
  3416. * const res = await MyModel.findOne().map(res => {
  3417. * // Sets a `loadedAt` property on the doc that tells you the time the
  3418. * // document was loaded.
  3419. * return res == null ?
  3420. * res :
  3421. * Object.assign(res, { loadedAt: new Date() });
  3422. * });
  3423. *
  3424. * @method map
  3425. * @memberOf Query
  3426. * @instance
  3427. * @param {Function} fn function to run to transform the query result
  3428. * @return {Query} this
  3429. */
  3430. Query.prototype.map = function(fn) {
  3431. this._transforms.push(fn);
  3432. return this;
  3433. };
  3434. /**
  3435. * Make this query throw an error if no documents match the given `filter`.
  3436. * This is handy for integrating with async/await, because `orFail()` saves you
  3437. * an extra `if` statement to check if no document was found.
  3438. *
  3439. * ####Example:
  3440. *
  3441. * // Throws if no doc returned
  3442. * await Model.findOne({ foo: 'bar' }).orFail();
  3443. *
  3444. * // Throws if no document was updated
  3445. * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
  3446. *
  3447. * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
  3448. * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
  3449. *
  3450. * // Throws "Not found" error if no document was found
  3451. * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
  3452. * orFail(() => Error('Not found'));
  3453. *
  3454. * @method orFail
  3455. * @memberOf Query
  3456. * @instance
  3457. * @param {Function|Error} [err] optional error to throw if no docs match `filter`
  3458. * @return {Query} this
  3459. */
  3460. Query.prototype.orFail = function(err) {
  3461. this.map(res => {
  3462. switch (this.op) {
  3463. case 'find':
  3464. if (res.length === 0) {
  3465. err = typeof err === 'function' ? err.call(this) : err;
  3466. throw err;
  3467. }
  3468. break;
  3469. case 'findOne':
  3470. if (res == null) {
  3471. err = typeof err === 'function' ? err.call(this) : err;
  3472. throw err;
  3473. }
  3474. break;
  3475. case 'update':
  3476. case 'updateMany':
  3477. case 'updateOne':
  3478. if (get(res, 'result.nModified') === 0) {
  3479. err = typeof err === 'function' ? err.call(this) : err;
  3480. throw err;
  3481. }
  3482. break;
  3483. case 'findOneAndDelete':
  3484. if (get(res, 'lastErrorObject.n') === 0) {
  3485. err = typeof err === 'function' ? err.call(this) : err;
  3486. throw err;
  3487. }
  3488. break;
  3489. case 'findOneAndUpdate':
  3490. if (get(res, 'lastErrorObject.updatedExisting') === false) {
  3491. err = typeof err === 'function' ? err.call(this) : err;
  3492. throw err;
  3493. }
  3494. break;
  3495. case 'deleteMany':
  3496. case 'deleteOne':
  3497. case 'remove':
  3498. if (res.n === 0) {
  3499. err = typeof err === 'function' ? err.call(this) : err;
  3500. throw err;
  3501. }
  3502. break;
  3503. default:
  3504. break;
  3505. }
  3506. return res;
  3507. });
  3508. return this;
  3509. };
  3510. /**
  3511. * Executes the query
  3512. *
  3513. * ####Examples:
  3514. *
  3515. * var promise = query.exec();
  3516. * var promise = query.exec('update');
  3517. *
  3518. * query.exec(callback);
  3519. * query.exec('find', callback);
  3520. *
  3521. * @param {String|Function} [operation]
  3522. * @param {Function} [callback] optional params depend on the function being called
  3523. * @return {Promise}
  3524. * @api public
  3525. */
  3526. Query.prototype.exec = function exec(op, callback) {
  3527. const _this = this;
  3528. if (typeof op === 'function') {
  3529. callback = op;
  3530. op = null;
  3531. } else if (typeof op === 'string') {
  3532. this.op = op;
  3533. }
  3534. if (callback != null) {
  3535. callback = this.model.$wrapCallback(callback);
  3536. }
  3537. return utils.promiseOrCallback(callback, (cb) => {
  3538. if (!_this.op) {
  3539. cb();
  3540. return;
  3541. }
  3542. this._hooks.execPre('exec', this, [], (error) => {
  3543. if (error) {
  3544. return cb(error);
  3545. }
  3546. this[this.op].call(this, (error, res) => {
  3547. if (error) {
  3548. return cb(error);
  3549. }
  3550. this._hooks.execPost('exec', this, [], {}, (error) => {
  3551. if (error) {
  3552. return cb(error);
  3553. }
  3554. cb(null, res);
  3555. });
  3556. });
  3557. });
  3558. }, this.model.events);
  3559. };
  3560. /*!
  3561. * ignore
  3562. */
  3563. function _wrapThunkCallback(query, cb) {
  3564. return function(error, res) {
  3565. if (error != null) {
  3566. return cb(error);
  3567. }
  3568. for (const fn of query._transforms) {
  3569. try {
  3570. res = fn(res);
  3571. } catch (error) {
  3572. return cb(error);
  3573. }
  3574. }
  3575. return cb(null, res);
  3576. };
  3577. }
  3578. /**
  3579. * Executes the query returning a `Promise` which will be
  3580. * resolved with either the doc(s) or rejected with the error.
  3581. *
  3582. * @param {Function} [resolve]
  3583. * @param {Function} [reject]
  3584. * @return {Promise}
  3585. * @api public
  3586. */
  3587. Query.prototype.then = function(resolve, reject) {
  3588. return this.exec().then(resolve, reject);
  3589. };
  3590. /**
  3591. * Executes the query returning a `Promise` which will be
  3592. * resolved with either the doc(s) or rejected with the error.
  3593. * Like `.then()`, but only takes a rejection handler.
  3594. *
  3595. * @param {Function} [reject]
  3596. * @return {Promise}
  3597. * @api public
  3598. */
  3599. Query.prototype.catch = function(reject) {
  3600. return this.exec().then(null, reject);
  3601. };
  3602. /*!
  3603. * ignore
  3604. */
  3605. Query.prototype._pre = function(fn) {
  3606. this._hooks.pre('exec', fn);
  3607. return this;
  3608. };
  3609. /*!
  3610. * ignore
  3611. */
  3612. Query.prototype._post = function(fn) {
  3613. this._hooks.post('exec', fn);
  3614. return this;
  3615. };
  3616. /*!
  3617. * Casts obj for an update command.
  3618. *
  3619. * @param {Object} obj
  3620. * @return {Object} obj after casting its values
  3621. * @api private
  3622. */
  3623. Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
  3624. let strict;
  3625. if ('strict' in this._mongooseOptions) {
  3626. strict = this._mongooseOptions.strict;
  3627. } else if (this.schema && this.schema.options) {
  3628. strict = this.schema.options.strict;
  3629. } else {
  3630. strict = true;
  3631. }
  3632. let omitUndefined = false;
  3633. if ('omitUndefined' in this._mongooseOptions) {
  3634. omitUndefined = this._mongooseOptions.omitUndefined;
  3635. }
  3636. let useNestedStrict;
  3637. if ('useNestedStrict' in this.options) {
  3638. useNestedStrict = this.options.useNestedStrict;
  3639. }
  3640. return castUpdate(this.schema, obj, {
  3641. overwrite: overwrite,
  3642. strict: strict,
  3643. omitUndefined,
  3644. useNestedStrict: useNestedStrict
  3645. }, this, this._conditions);
  3646. };
  3647. /*!
  3648. * castQuery
  3649. * @api private
  3650. */
  3651. function castQuery(query) {
  3652. try {
  3653. return query.cast(query.model);
  3654. } catch (err) {
  3655. return err;
  3656. }
  3657. }
  3658. /*!
  3659. * castDoc
  3660. * @api private
  3661. */
  3662. function castDoc(query, overwrite) {
  3663. try {
  3664. return query._castUpdate(query._update, overwrite);
  3665. } catch (err) {
  3666. return err;
  3667. }
  3668. }
  3669. /**
  3670. * Specifies paths which should be populated with other documents.
  3671. *
  3672. * ####Example:
  3673. *
  3674. * Kitten.findOne().populate('owner').exec(function (err, kitten) {
  3675. * console.log(kitten.owner.name) // Max
  3676. * })
  3677. *
  3678. * Kitten.find().populate({
  3679. * path: 'owner'
  3680. * , select: 'name'
  3681. * , match: { color: 'black' }
  3682. * , options: { sort: { name: -1 }}
  3683. * }).exec(function (err, kittens) {
  3684. * console.log(kittens[0].owner.name) // Zoopa
  3685. * })
  3686. *
  3687. * // alternatively
  3688. * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
  3689. * console.log(kittens[0].owner.name) // Zoopa
  3690. * })
  3691. *
  3692. * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.
  3693. *
  3694. * @param {Object|String} path either the path to populate or an object specifying all parameters
  3695. * @param {Object|String} [select] Field selection for the population query
  3696. * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field.
  3697. * @param {Object} [match] Conditions for the population query
  3698. * @param {Object} [options] Options for the population query (sort, etc)
  3699. * @see population ./populate.html
  3700. * @see Query#select #query_Query-select
  3701. * @see Model.populate #model_Model.populate
  3702. * @return {Query} this
  3703. * @api public
  3704. */
  3705. Query.prototype.populate = function() {
  3706. if (arguments.length === 0) {
  3707. return this;
  3708. }
  3709. const res = utils.populate.apply(null, arguments);
  3710. // Propagate readConcern and readPreference and lean from parent query,
  3711. // unless one already specified
  3712. if (this.options != null) {
  3713. const readConcern = this.options.readConcern;
  3714. const readPref = this.options.readPreference;
  3715. for (let i = 0; i < res.length; ++i) {
  3716. if (readConcern != null && get(res[i], 'options.readConcern') == null) {
  3717. res[i].options = res[i].options || {};
  3718. res[i].options.readConcern = readConcern;
  3719. }
  3720. if (readPref != null && get(res[i], 'options.readPreference') == null) {
  3721. res[i].options = res[i].options || {};
  3722. res[i].options.readPreference = readPref;
  3723. }
  3724. }
  3725. }
  3726. const opts = this._mongooseOptions;
  3727. if (opts.lean != null) {
  3728. const lean = opts.lean;
  3729. for (let i = 0; i < res.length; ++i) {
  3730. if (get(res[i], 'options.lean') == null) {
  3731. res[i].options = res[i].options || {};
  3732. res[i].options.lean = lean;
  3733. }
  3734. }
  3735. }
  3736. if (!utils.isObject(opts.populate)) {
  3737. opts.populate = {};
  3738. }
  3739. const pop = opts.populate;
  3740. for (let i = 0; i < res.length; ++i) {
  3741. const path = res[i].path;
  3742. if (pop[path] && pop[path].populate && res[i].populate) {
  3743. res[i].populate = pop[path].populate.concat(res[i].populate);
  3744. }
  3745. pop[res[i].path] = res[i];
  3746. }
  3747. return this;
  3748. };
  3749. /**
  3750. * Gets a list of paths to be populated by this query
  3751. *
  3752. * ####Example:
  3753. * bookSchema.pre('findOne', function() {
  3754. * let keys = this.getPopulatedPaths(); // ['author']
  3755. * })
  3756. * ...
  3757. * Book.findOne({}).populate('author')
  3758. *
  3759. * @return {Array} an array of strings representing populated paths
  3760. * @api public
  3761. */
  3762. Query.prototype.getPopulatedPaths = function getPopulatedPaths() {
  3763. const obj = this._mongooseOptions.populate || {};
  3764. return Object.keys(obj);
  3765. };
  3766. /**
  3767. * Casts this query to the schema of `model`
  3768. *
  3769. * ####Note
  3770. *
  3771. * If `obj` is present, it is cast instead of this query.
  3772. *
  3773. * @param {Model} [model] the model to cast to. If not set, defaults to `this.model`
  3774. * @param {Object} [obj]
  3775. * @return {Object}
  3776. * @api public
  3777. */
  3778. Query.prototype.cast = function(model, obj) {
  3779. obj || (obj = this._conditions);
  3780. model = model || this.model;
  3781. try {
  3782. return cast(model.schema, obj, {
  3783. upsert: this.options && this.options.upsert,
  3784. strict: (this.options && 'strict' in this.options) ?
  3785. this.options.strict :
  3786. get(model, 'schema.options.strict', null),
  3787. strictQuery: (this.options && this.options.strictQuery) ||
  3788. get(model, 'schema.options.strictQuery', null)
  3789. }, this);
  3790. } catch (err) {
  3791. // CastError, assign model
  3792. if (typeof err.setModel === 'function') {
  3793. err.setModel(model);
  3794. }
  3795. throw err;
  3796. }
  3797. };
  3798. /**
  3799. * Casts selected field arguments for field selection with mongo 2.2
  3800. *
  3801. * query.select({ ids: { $elemMatch: { $in: [hexString] }})
  3802. *
  3803. * @param {Object} fields
  3804. * @see https://github.com/Automattic/mongoose/issues/1091
  3805. * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/
  3806. * @api private
  3807. */
  3808. Query.prototype._castFields = function _castFields(fields) {
  3809. let selected,
  3810. elemMatchKeys,
  3811. keys,
  3812. key,
  3813. out,
  3814. i;
  3815. if (fields) {
  3816. keys = Object.keys(fields);
  3817. elemMatchKeys = [];
  3818. i = keys.length;
  3819. // collect $elemMatch args
  3820. while (i--) {
  3821. key = keys[i];
  3822. if (fields[key].$elemMatch) {
  3823. selected || (selected = {});
  3824. selected[key] = fields[key];
  3825. elemMatchKeys.push(key);
  3826. }
  3827. }
  3828. }
  3829. if (selected) {
  3830. // they passed $elemMatch, cast em
  3831. try {
  3832. out = this.cast(this.model, selected);
  3833. } catch (err) {
  3834. return err;
  3835. }
  3836. // apply the casted field args
  3837. i = elemMatchKeys.length;
  3838. while (i--) {
  3839. key = elemMatchKeys[i];
  3840. fields[key] = out[key];
  3841. }
  3842. }
  3843. return fields;
  3844. };
  3845. /**
  3846. * Applies schematype selected options to this query.
  3847. * @api private
  3848. */
  3849. Query.prototype._applyPaths = function applyPaths() {
  3850. this._fields = this._fields || {};
  3851. helpers.applyPaths(this._fields, this.model.schema);
  3852. let _selectPopulatedPaths = true;
  3853. if ('selectPopulatedPaths' in this.model.base.options) {
  3854. _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths;
  3855. }
  3856. if ('selectPopulatedPaths' in this.model.schema.options) {
  3857. _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths;
  3858. }
  3859. if (_selectPopulatedPaths) {
  3860. selectPopulatedFields(this);
  3861. }
  3862. };
  3863. /**
  3864. * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
  3865. * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
  3866. *
  3867. * The `.cursor()` function triggers pre find hooks, but **not** post find hooks.
  3868. *
  3869. * ####Example
  3870. *
  3871. * // There are 2 ways to use a cursor. First, as a stream:
  3872. * Thing.
  3873. * find({ name: /^hello/ }).
  3874. * cursor().
  3875. * on('data', function(doc) { console.log(doc); }).
  3876. * on('end', function() { console.log('Done!'); });
  3877. *
  3878. * // Or you can use `.next()` to manually get the next doc in the stream.
  3879. * // `.next()` returns a promise, so you can use promises or callbacks.
  3880. * var cursor = Thing.find({ name: /^hello/ }).cursor();
  3881. * cursor.next(function(error, doc) {
  3882. * console.log(doc);
  3883. * });
  3884. *
  3885. * // Because `.next()` returns a promise, you can use co
  3886. * // to easily iterate through all documents without loading them
  3887. * // all into memory.
  3888. * co(function*() {
  3889. * const cursor = Thing.find({ name: /^hello/ }).cursor();
  3890. * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
  3891. * console.log(doc);
  3892. * }
  3893. * });
  3894. *
  3895. * ####Valid options
  3896. *
  3897. * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`.
  3898. *
  3899. * @return {QueryCursor}
  3900. * @param {Object} [options]
  3901. * @see QueryCursor
  3902. * @api public
  3903. */
  3904. Query.prototype.cursor = function cursor(opts) {
  3905. this._applyPaths();
  3906. this._fields = this._castFields(this._fields);
  3907. this.setOptions({ projection: this._fieldsForExec() });
  3908. if (opts) {
  3909. this.setOptions(opts);
  3910. }
  3911. try {
  3912. this.cast(this.model);
  3913. } catch (err) {
  3914. return (new QueryCursor(this, this.options))._markError(err);
  3915. }
  3916. return new QueryCursor(this, this.options);
  3917. };
  3918. // the rest of these are basically to support older Mongoose syntax with mquery
  3919. /**
  3920. * _DEPRECATED_ Alias of `maxScan`
  3921. *
  3922. * @deprecated
  3923. * @see maxScan #query_Query-maxScan
  3924. * @method maxscan
  3925. * @memberOf Query
  3926. * @instance
  3927. */
  3928. Query.prototype.maxscan = Query.base.maxScan;
  3929. /**
  3930. * Sets the tailable option (for use with capped collections).
  3931. *
  3932. * ####Example
  3933. *
  3934. * query.tailable() // true
  3935. * query.tailable(true)
  3936. * query.tailable(false)
  3937. *
  3938. * ####Note
  3939. *
  3940. * Cannot be used with `distinct()`
  3941. *
  3942. * @param {Boolean} bool defaults to true
  3943. * @param {Object} [opts] options to set
  3944. * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up
  3945. * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying
  3946. * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/
  3947. * @api public
  3948. */
  3949. Query.prototype.tailable = function(val, opts) {
  3950. // we need to support the tailable({ awaitdata : true }) as well as the
  3951. // tailable(true, {awaitdata :true}) syntax that mquery does not support
  3952. if (val && val.constructor.name === 'Object') {
  3953. opts = val;
  3954. val = true;
  3955. }
  3956. if (val === undefined) {
  3957. val = true;
  3958. }
  3959. if (opts && typeof opts === 'object') {
  3960. for (const key in opts) {
  3961. if (key === 'awaitdata') {
  3962. // For backwards compatibility
  3963. this.options[key] = !!opts[key];
  3964. } else {
  3965. this.options[key] = opts[key];
  3966. }
  3967. }
  3968. }
  3969. return Query.base.tailable.call(this, val);
  3970. };
  3971. /**
  3972. * Declares an intersects query for `geometry()`.
  3973. *
  3974. * ####Example
  3975. *
  3976. * query.where('path').intersects().geometry({
  3977. * type: 'LineString'
  3978. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  3979. * })
  3980. *
  3981. * query.where('path').intersects({
  3982. * type: 'LineString'
  3983. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  3984. * })
  3985. *
  3986. * ####NOTE:
  3987. *
  3988. * **MUST** be used after `where()`.
  3989. *
  3990. * ####NOTE:
  3991. *
  3992. * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within).
  3993. *
  3994. * @method intersects
  3995. * @memberOf Query
  3996. * @instance
  3997. * @param {Object} [arg]
  3998. * @return {Query} this
  3999. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  4000. * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/
  4001. * @api public
  4002. */
  4003. /**
  4004. * Specifies a `$geometry` condition
  4005. *
  4006. * ####Example
  4007. *
  4008. * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
  4009. * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
  4010. *
  4011. * // or
  4012. * var polyB = [[ 0, 0 ], [ 1, 1 ]]
  4013. * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
  4014. *
  4015. * // or
  4016. * var polyC = [ 0, 0 ]
  4017. * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
  4018. *
  4019. * // or
  4020. * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
  4021. *
  4022. * The argument is assigned to the most recent path passed to `where()`.
  4023. *
  4024. * ####NOTE:
  4025. *
  4026. * `geometry()` **must** come after either `intersects()` or `within()`.
  4027. *
  4028. * The `object` argument must contain `type` and `coordinates` properties.
  4029. * - type {String}
  4030. * - coordinates {Array}
  4031. *
  4032. * @method geometry
  4033. * @memberOf Query
  4034. * @instance
  4035. * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
  4036. * @return {Query} this
  4037. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  4038. * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
  4039. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4040. * @api public
  4041. */
  4042. /**
  4043. * Specifies a `$near` or `$nearSphere` condition
  4044. *
  4045. * These operators return documents sorted by distance.
  4046. *
  4047. * ####Example
  4048. *
  4049. * query.where('loc').near({ center: [10, 10] });
  4050. * query.where('loc').near({ center: [10, 10], maxDistance: 5 });
  4051. * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
  4052. * query.near('loc', { center: [10, 10], maxDistance: 5 });
  4053. *
  4054. * @method near
  4055. * @memberOf Query
  4056. * @instance
  4057. * @param {String} [path]
  4058. * @param {Object} val
  4059. * @return {Query} this
  4060. * @see $near http://docs.mongodb.org/manual/reference/operator/near/
  4061. * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
  4062. * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
  4063. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4064. * @api public
  4065. */
  4066. /*!
  4067. * Overwriting mquery is needed to support a couple different near() forms found in older
  4068. * versions of mongoose
  4069. * near([1,1])
  4070. * near(1,1)
  4071. * near(field, [1,2])
  4072. * near(field, 1, 2)
  4073. * In addition to all of the normal forms supported by mquery
  4074. */
  4075. Query.prototype.near = function() {
  4076. const params = [];
  4077. const sphere = this._mongooseOptions.nearSphere;
  4078. // TODO refactor
  4079. if (arguments.length === 1) {
  4080. if (Array.isArray(arguments[0])) {
  4081. params.push({center: arguments[0], spherical: sphere});
  4082. } else if (typeof arguments[0] === 'string') {
  4083. // just passing a path
  4084. params.push(arguments[0]);
  4085. } else if (utils.isObject(arguments[0])) {
  4086. if (typeof arguments[0].spherical !== 'boolean') {
  4087. arguments[0].spherical = sphere;
  4088. }
  4089. params.push(arguments[0]);
  4090. } else {
  4091. throw new TypeError('invalid argument');
  4092. }
  4093. } else if (arguments.length === 2) {
  4094. if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
  4095. params.push({center: [arguments[0], arguments[1]], spherical: sphere});
  4096. } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) {
  4097. params.push(arguments[0]);
  4098. params.push({center: arguments[1], spherical: sphere});
  4099. } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) {
  4100. params.push(arguments[0]);
  4101. if (typeof arguments[1].spherical !== 'boolean') {
  4102. arguments[1].spherical = sphere;
  4103. }
  4104. params.push(arguments[1]);
  4105. } else {
  4106. throw new TypeError('invalid argument');
  4107. }
  4108. } else if (arguments.length === 3) {
  4109. if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number'
  4110. && typeof arguments[2] === 'number') {
  4111. params.push(arguments[0]);
  4112. params.push({center: [arguments[1], arguments[2]], spherical: sphere});
  4113. } else {
  4114. throw new TypeError('invalid argument');
  4115. }
  4116. } else {
  4117. throw new TypeError('invalid argument');
  4118. }
  4119. return Query.base.near.apply(this, params);
  4120. };
  4121. /**
  4122. * _DEPRECATED_ Specifies a `$nearSphere` condition
  4123. *
  4124. * ####Example
  4125. *
  4126. * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
  4127. *
  4128. * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
  4129. *
  4130. * ####Example
  4131. *
  4132. * query.where('loc').near({ center: [10, 10], spherical: true });
  4133. *
  4134. * @deprecated
  4135. * @see near() #query_Query-near
  4136. * @see $near http://docs.mongodb.org/manual/reference/operator/near/
  4137. * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
  4138. * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
  4139. */
  4140. Query.prototype.nearSphere = function() {
  4141. this._mongooseOptions.nearSphere = true;
  4142. this.near.apply(this, arguments);
  4143. return this;
  4144. };
  4145. /**
  4146. * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators)
  4147. * This function *only* works for `find()` queries.
  4148. * You do not need to call this function explicitly, the JavaScript runtime
  4149. * will call it for you.
  4150. *
  4151. * ####Example
  4152. *
  4153. * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
  4154. * console.log(doc.name);
  4155. * }
  4156. *
  4157. * Node.js 10.x supports async iterators natively without any flags. You can
  4158. * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
  4159. *
  4160. * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If
  4161. * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
  4162. * support async iterators.
  4163. *
  4164. * @method Symbol.asyncIterator
  4165. * @memberOf Query
  4166. * @instance
  4167. * @api public
  4168. */
  4169. if (Symbol.asyncIterator != null) {
  4170. Query.prototype[Symbol.asyncIterator] = function() {
  4171. return this.cursor().transformNull().map(doc => {
  4172. return doc == null ? { done: true } : { value: doc, done: false };
  4173. });
  4174. };
  4175. }
  4176. /**
  4177. * Specifies a $polygon condition
  4178. *
  4179. * ####Example
  4180. *
  4181. * query.where('loc').within().polygon([10,20], [13, 25], [7,15])
  4182. * query.polygon('loc', [10,20], [13, 25], [7,15])
  4183. *
  4184. * @method polygon
  4185. * @memberOf Query
  4186. * @instance
  4187. * @param {String|Array} [path]
  4188. * @param {Array|Object} [coordinatePairs...]
  4189. * @return {Query} this
  4190. * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
  4191. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4192. * @api public
  4193. */
  4194. /**
  4195. * Specifies a $box condition
  4196. *
  4197. * ####Example
  4198. *
  4199. * var lowerLeft = [40.73083, -73.99756]
  4200. * var upperRight= [40.741404, -73.988135]
  4201. *
  4202. * query.where('loc').within().box(lowerLeft, upperRight)
  4203. * query.box({ ll : lowerLeft, ur : upperRight })
  4204. *
  4205. * @method box
  4206. * @memberOf Query
  4207. * @instance
  4208. * @see $box http://docs.mongodb.org/manual/reference/operator/box/
  4209. * @see within() Query#within #query_Query-within
  4210. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4211. * @param {Object} val
  4212. * @param [Array] Upper Right Coords
  4213. * @return {Query} this
  4214. * @api public
  4215. */
  4216. /*!
  4217. * this is needed to support the mongoose syntax of:
  4218. * box(field, { ll : [x,y], ur : [x2,y2] })
  4219. * box({ ll : [x,y], ur : [x2,y2] })
  4220. */
  4221. Query.prototype.box = function(ll, ur) {
  4222. if (!Array.isArray(ll) && utils.isObject(ll)) {
  4223. ur = ll.ur;
  4224. ll = ll.ll;
  4225. }
  4226. return Query.base.box.call(this, ll, ur);
  4227. };
  4228. /**
  4229. * Specifies a $center or $centerSphere condition.
  4230. *
  4231. * ####Example
  4232. *
  4233. * var area = { center: [50, 50], radius: 10, unique: true }
  4234. * query.where('loc').within().circle(area)
  4235. * // alternatively
  4236. * query.circle('loc', area);
  4237. *
  4238. * // spherical calculations
  4239. * var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
  4240. * query.where('loc').within().circle(area)
  4241. * // alternatively
  4242. * query.circle('loc', area);
  4243. *
  4244. * New in 3.7.0
  4245. *
  4246. * @method circle
  4247. * @memberOf Query
  4248. * @instance
  4249. * @param {String} [path]
  4250. * @param {Object} area
  4251. * @return {Query} this
  4252. * @see $center http://docs.mongodb.org/manual/reference/operator/center/
  4253. * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
  4254. * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/
  4255. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4256. * @api public
  4257. */
  4258. /**
  4259. * _DEPRECATED_ Alias for [circle](#query_Query-circle)
  4260. *
  4261. * **Deprecated.** Use [circle](#query_Query-circle) instead.
  4262. *
  4263. * @deprecated
  4264. * @method center
  4265. * @memberOf Query
  4266. * @instance
  4267. * @api public
  4268. */
  4269. Query.prototype.center = Query.base.circle;
  4270. /**
  4271. * _DEPRECATED_ Specifies a $centerSphere condition
  4272. *
  4273. * **Deprecated.** Use [circle](#query_Query-circle) instead.
  4274. *
  4275. * ####Example
  4276. *
  4277. * var area = { center: [50, 50], radius: 10 };
  4278. * query.where('loc').within().centerSphere(area);
  4279. *
  4280. * @deprecated
  4281. * @param {String} [path]
  4282. * @param {Object} val
  4283. * @return {Query} this
  4284. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4285. * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
  4286. * @api public
  4287. */
  4288. Query.prototype.centerSphere = function() {
  4289. if (arguments[0] && arguments[0].constructor.name === 'Object') {
  4290. arguments[0].spherical = true;
  4291. }
  4292. if (arguments[1] && arguments[1].constructor.name === 'Object') {
  4293. arguments[1].spherical = true;
  4294. }
  4295. Query.base.circle.apply(this, arguments);
  4296. };
  4297. /**
  4298. * Determines if field selection has been made.
  4299. *
  4300. * @method selected
  4301. * @memberOf Query
  4302. * @instance
  4303. * @return {Boolean}
  4304. * @api public
  4305. */
  4306. /**
  4307. * Determines if inclusive field selection has been made.
  4308. *
  4309. * query.selectedInclusively() // false
  4310. * query.select('name')
  4311. * query.selectedInclusively() // true
  4312. *
  4313. * @method selectedInclusively
  4314. * @memberOf Query
  4315. * @instance
  4316. * @return {Boolean}
  4317. * @api public
  4318. */
  4319. Query.prototype.selectedInclusively = function selectedInclusively() {
  4320. return isInclusive(this._fields);
  4321. };
  4322. /**
  4323. * Determines if exclusive field selection has been made.
  4324. *
  4325. * query.selectedExclusively() // false
  4326. * query.select('-name')
  4327. * query.selectedExclusively() // true
  4328. * query.selectedInclusively() // false
  4329. *
  4330. * @method selectedExclusively
  4331. * @memberOf Query
  4332. * @instance
  4333. * @return {Boolean}
  4334. * @api public
  4335. */
  4336. Query.prototype.selectedExclusively = function selectedExclusively() {
  4337. if (!this._fields) {
  4338. return false;
  4339. }
  4340. const keys = Object.keys(this._fields);
  4341. if (keys.length === 0) {
  4342. return false;
  4343. }
  4344. for (let i = 0; i < keys.length; ++i) {
  4345. const key = keys[i];
  4346. if (key === '_id') {
  4347. continue;
  4348. }
  4349. if (this._fields[key] === 0 || this._fields[key] === false) {
  4350. return true;
  4351. }
  4352. }
  4353. return false;
  4354. };
  4355. /*!
  4356. * Export
  4357. */
  4358. module.exports = Query;