query.js 139 KB

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