query.js 149 KB

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