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

query.js 150KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154
  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 && !this.options.rawResult) {
  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#deleteMany()` 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. if (options.rawResult && doc == null) {
  2426. _init(null);
  2427. return null;
  2428. }
  2429. const casted = helpers.createModel(model, doc, fields, userProvidedFields);
  2430. try {
  2431. casted.init(doc, opts, _init);
  2432. } catch (error) {
  2433. _init(error);
  2434. }
  2435. function _init(err) {
  2436. if (err) {
  2437. return process.nextTick(() => callback(err));
  2438. }
  2439. if (options.rawResult) {
  2440. if (doc && casted) {
  2441. casted.$session(options.session);
  2442. res.value = casted;
  2443. } else {
  2444. res.value = null;
  2445. }
  2446. return process.nextTick(() => callback(null, res));
  2447. }
  2448. casted.$session(options.session);
  2449. process.nextTick(() => callback(null, casted));
  2450. }
  2451. }
  2452. /*!
  2453. * If the model is a discriminator type and not root, then add the key & value to the criteria.
  2454. */
  2455. function prepareDiscriminatorCriteria(query) {
  2456. if (!query || !query.model || !query.model.schema) {
  2457. return;
  2458. }
  2459. const schema = query.model.schema;
  2460. if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) {
  2461. query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value;
  2462. }
  2463. }
  2464. /**
  2465. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.
  2466. *
  2467. * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found
  2468. * document (if any) to the callback. The query executes if
  2469. * `callback` is passed.
  2470. *
  2471. * This function triggers the following middleware.
  2472. *
  2473. * - `findOneAndUpdate()`
  2474. *
  2475. * ####Available options
  2476. *
  2477. * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  2478. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  2479. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
  2480. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2481. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2482. * - `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.
  2483. * - `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/).
  2484. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2485. * - `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.
  2486. *
  2487. * ####Callback Signature
  2488. * function(error, doc) {
  2489. * // error: any errors that occurred
  2490. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2491. * }
  2492. *
  2493. * ####Examples
  2494. *
  2495. * query.findOneAndUpdate(conditions, update, options, callback) // executes
  2496. * query.findOneAndUpdate(conditions, update, options) // returns Query
  2497. * query.findOneAndUpdate(conditions, update, callback) // executes
  2498. * query.findOneAndUpdate(conditions, update) // returns Query
  2499. * query.findOneAndUpdate(update, callback) // returns Query
  2500. * query.findOneAndUpdate(update) // returns Query
  2501. * query.findOneAndUpdate(callback) // executes
  2502. * query.findOneAndUpdate() // returns Query
  2503. *
  2504. * @method findOneAndUpdate
  2505. * @memberOf Query
  2506. * @instance
  2507. * @param {Object|Query} [query]
  2508. * @param {Object} [doc]
  2509. * @param {Object} [options]
  2510. * @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)
  2511. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2512. * @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.
  2513. * @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).
  2514. * @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.
  2515. * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult)
  2516. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2517. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  2518. * @return {Query} this
  2519. * @api public
  2520. */
  2521. Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) {
  2522. this.op = 'findOneAndUpdate';
  2523. this._validate();
  2524. switch (arguments.length) {
  2525. case 3:
  2526. if (typeof options === 'function') {
  2527. callback = options;
  2528. options = {};
  2529. }
  2530. break;
  2531. case 2:
  2532. if (typeof doc === 'function') {
  2533. callback = doc;
  2534. doc = criteria;
  2535. criteria = undefined;
  2536. }
  2537. options = undefined;
  2538. break;
  2539. case 1:
  2540. if (typeof criteria === 'function') {
  2541. callback = criteria;
  2542. criteria = options = doc = undefined;
  2543. } else {
  2544. doc = criteria;
  2545. criteria = options = undefined;
  2546. }
  2547. }
  2548. if (mquery.canMerge(criteria)) {
  2549. this.merge(criteria);
  2550. }
  2551. // apply doc
  2552. if (doc) {
  2553. this._mergeUpdate(doc);
  2554. }
  2555. if (options) {
  2556. options = utils.clone(options);
  2557. if (options.projection) {
  2558. this.select(options.projection);
  2559. delete options.projection;
  2560. }
  2561. if (options.fields) {
  2562. this.select(options.fields);
  2563. delete options.fields;
  2564. }
  2565. this.setOptions(options);
  2566. }
  2567. if (!callback) {
  2568. return this;
  2569. }
  2570. this._findOneAndUpdate(callback);
  2571. return this;
  2572. };
  2573. /*!
  2574. * Thunk around findOneAndUpdate()
  2575. *
  2576. * @param {Function} [callback]
  2577. * @api private
  2578. */
  2579. Query.prototype._findOneAndUpdate = wrapThunk(function(callback) {
  2580. if (this.error() != null) {
  2581. return callback(this.error());
  2582. }
  2583. this._findAndModify('update', callback);
  2584. });
  2585. /**
  2586. * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.
  2587. *
  2588. * Finds a matching document, removes it, passing the found document (if any) to
  2589. * the callback. Executes if `callback` is passed.
  2590. *
  2591. * This function triggers the following middleware.
  2592. *
  2593. * - `findOneAndRemove()`
  2594. *
  2595. * ####Available options
  2596. *
  2597. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2598. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2599. * - `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)
  2600. *
  2601. * ####Callback Signature
  2602. * function(error, doc) {
  2603. * // error: any errors that occurred
  2604. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2605. * }
  2606. *
  2607. * ####Examples
  2608. *
  2609. * A.where().findOneAndRemove(conditions, options, callback) // executes
  2610. * A.where().findOneAndRemove(conditions, options) // return Query
  2611. * A.where().findOneAndRemove(conditions, callback) // executes
  2612. * A.where().findOneAndRemove(conditions) // returns Query
  2613. * A.where().findOneAndRemove(callback) // executes
  2614. * A.where().findOneAndRemove() // returns Query
  2615. *
  2616. * @method findOneAndRemove
  2617. * @memberOf Query
  2618. * @instance
  2619. * @param {Object} [conditions]
  2620. * @param {Object} [options]
  2621. * @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)
  2622. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2623. * @param {Function} [callback] optional params are (error, document)
  2624. * @return {Query} this
  2625. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2626. * @api public
  2627. */
  2628. Query.prototype.findOneAndRemove = function(conditions, options, callback) {
  2629. this.op = 'findOneAndRemove';
  2630. this._validate();
  2631. switch (arguments.length) {
  2632. case 2:
  2633. if (typeof options === 'function') {
  2634. callback = options;
  2635. options = {};
  2636. }
  2637. break;
  2638. case 1:
  2639. if (typeof conditions === 'function') {
  2640. callback = conditions;
  2641. conditions = undefined;
  2642. options = undefined;
  2643. }
  2644. break;
  2645. }
  2646. if (mquery.canMerge(conditions)) {
  2647. this.merge(conditions);
  2648. }
  2649. options && this.setOptions(options);
  2650. if (!callback) {
  2651. return this;
  2652. }
  2653. this._findOneAndRemove(callback);
  2654. return this;
  2655. };
  2656. /**
  2657. * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command.
  2658. *
  2659. * Finds a matching document, removes it, and passes the found document (if any)
  2660. * to the callback. Executes if `callback` is passed.
  2661. *
  2662. * This function triggers the following middleware.
  2663. *
  2664. * - `findOneAndDelete()`
  2665. *
  2666. * This function differs slightly from `Model.findOneAndRemove()` in that
  2667. * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/),
  2668. * as opposed to a `findOneAndDelete()` command. For most mongoose use cases,
  2669. * this distinction is purely pedantic. You should use `findOneAndDelete()`
  2670. * unless you have a good reason not to.
  2671. *
  2672. * ####Available options
  2673. *
  2674. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2675. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2676. * - `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)
  2677. *
  2678. * ####Callback Signature
  2679. * function(error, doc) {
  2680. * // error: any errors that occurred
  2681. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2682. * }
  2683. *
  2684. * ####Examples
  2685. *
  2686. * A.where().findOneAndDelete(conditions, options, callback) // executes
  2687. * A.where().findOneAndDelete(conditions, options) // return Query
  2688. * A.where().findOneAndDelete(conditions, callback) // executes
  2689. * A.where().findOneAndDelete(conditions) // returns Query
  2690. * A.where().findOneAndDelete(callback) // executes
  2691. * A.where().findOneAndDelete() // returns Query
  2692. *
  2693. * @method findOneAndDelete
  2694. * @memberOf Query
  2695. * @param {Object} [conditions]
  2696. * @param {Object} [options]
  2697. * @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)
  2698. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2699. * @param {Function} [callback] optional params are (error, document)
  2700. * @return {Query} this
  2701. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2702. * @api public
  2703. */
  2704. Query.prototype.findOneAndDelete = function(conditions, options, callback) {
  2705. this.op = 'findOneAndDelete';
  2706. this._validate();
  2707. switch (arguments.length) {
  2708. case 2:
  2709. if (typeof options === 'function') {
  2710. callback = options;
  2711. options = {};
  2712. }
  2713. break;
  2714. case 1:
  2715. if (typeof conditions === 'function') {
  2716. callback = conditions;
  2717. conditions = undefined;
  2718. options = undefined;
  2719. }
  2720. break;
  2721. }
  2722. if (mquery.canMerge(conditions)) {
  2723. this.merge(conditions);
  2724. }
  2725. options && this.setOptions(options);
  2726. if (!callback) {
  2727. return this;
  2728. }
  2729. this._findOneAndDelete(callback);
  2730. return this;
  2731. };
  2732. /*!
  2733. * Thunk around findOneAndDelete()
  2734. *
  2735. * @param {Function} [callback]
  2736. * @return {Query} this
  2737. * @api private
  2738. */
  2739. Query.prototype._findOneAndDelete = wrapThunk(function(callback) {
  2740. this._castConditions();
  2741. if (this.error() != null) {
  2742. callback(this.error());
  2743. return null;
  2744. }
  2745. const filter = this._conditions;
  2746. const options = this._optionsForExec();
  2747. let fields = null;
  2748. if (this._fields != null) {
  2749. options.projection = this._castFields(utils.clone(this._fields));
  2750. fields = options.projection;
  2751. if (fields instanceof Error) {
  2752. callback(fields);
  2753. return null;
  2754. }
  2755. }
  2756. this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => {
  2757. if (err) {
  2758. return callback(err);
  2759. }
  2760. const doc = res.value;
  2761. return this._completeOne(doc, res, callback);
  2762. }));
  2763. });
  2764. /**
  2765. * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command.
  2766. *
  2767. * Finds a matching document, removes it, and passes the found document (if any)
  2768. * to the callback. Executes if `callback` is passed.
  2769. *
  2770. * This function triggers the following middleware.
  2771. *
  2772. * - `findOneAndReplace()`
  2773. *
  2774. * ####Available options
  2775. *
  2776. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2777. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2778. * - `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)
  2779. *
  2780. * ####Callback Signature
  2781. * function(error, doc) {
  2782. * // error: any errors that occurred
  2783. * // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  2784. * }
  2785. *
  2786. * ####Examples
  2787. *
  2788. * A.where().findOneAndReplace(filter, replacement, options, callback); // executes
  2789. * A.where().findOneAndReplace(filter, replacement, options); // return Query
  2790. * A.where().findOneAndReplace(filter, replacement, callback); // executes
  2791. * A.where().findOneAndReplace(filter); // returns Query
  2792. * A.where().findOneAndReplace(callback); // executes
  2793. * A.where().findOneAndReplace(); // returns Query
  2794. *
  2795. * @method findOneAndReplace
  2796. * @memberOf Query
  2797. * @param {Object} [filter]
  2798. * @param {Object} [replacement]
  2799. * @param {Object} [options]
  2800. * @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)
  2801. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2802. * @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).
  2803. * @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.
  2804. * @param {Function} [callback] optional params are (error, document)
  2805. * @return {Query} this
  2806. * @api public
  2807. */
  2808. Query.prototype.findOneAndReplace = function(filter, replacement, options, callback) {
  2809. this.op = 'findOneAndReplace';
  2810. this._validate();
  2811. switch (arguments.length) {
  2812. case 3:
  2813. if (typeof options === 'function') {
  2814. callback = options;
  2815. options = void 0;
  2816. }
  2817. break;
  2818. case 2:
  2819. if (typeof replacement === 'function') {
  2820. callback = replacement;
  2821. replacement = void 0;
  2822. }
  2823. break;
  2824. case 1:
  2825. if (typeof filter === 'function') {
  2826. callback = filter;
  2827. filter = void 0;
  2828. replacement = void 0;
  2829. options = void 0;
  2830. }
  2831. break;
  2832. }
  2833. if (mquery.canMerge(filter)) {
  2834. this.merge(filter);
  2835. }
  2836. if (replacement != null) {
  2837. this._mergeUpdate(replacement);
  2838. }
  2839. options && this.setOptions(options);
  2840. if (!callback) {
  2841. return this;
  2842. }
  2843. this._findOneAndReplace(callback);
  2844. return this;
  2845. };
  2846. /*!
  2847. * Thunk around findOneAndReplace()
  2848. *
  2849. * @param {Function} [callback]
  2850. * @return {Query} this
  2851. * @api private
  2852. */
  2853. Query.prototype._findOneAndReplace = wrapThunk(function(callback) {
  2854. this._castConditions();
  2855. if (this.error() != null) {
  2856. callback(this.error());
  2857. return null;
  2858. }
  2859. const filter = this._conditions;
  2860. const options = this._optionsForExec();
  2861. let fields = null;
  2862. if (this._fields != null) {
  2863. options.projection = this._castFields(utils.clone(this._fields));
  2864. fields = options.projection;
  2865. if (fields instanceof Error) {
  2866. callback(fields);
  2867. return null;
  2868. }
  2869. }
  2870. this._collection.collection.findOneAndReplace(filter, options, (err, res) => {
  2871. if (err) {
  2872. return callback(err);
  2873. }
  2874. const doc = res.value;
  2875. return this._completeOne(doc, res, callback);
  2876. });
  2877. });
  2878. /*!
  2879. * Thunk around findOneAndRemove()
  2880. *
  2881. * @param {Function} [callback]
  2882. * @return {Query} this
  2883. * @api private
  2884. */
  2885. Query.prototype._findOneAndRemove = wrapThunk(function(callback) {
  2886. if (this.error() != null) {
  2887. callback(this.error());
  2888. return;
  2889. }
  2890. this._findAndModify('remove', callback);
  2891. });
  2892. /*!
  2893. * Get options from query opts, falling back to the base mongoose object.
  2894. */
  2895. function _getOption(query, option, def) {
  2896. const opts = query._optionsForExec(query.model);
  2897. if (option in opts) {
  2898. return opts[option];
  2899. }
  2900. if (option in query.model.base.options) {
  2901. return query.model.base.options[option];
  2902. }
  2903. return def;
  2904. }
  2905. /*!
  2906. * Override mquery.prototype._findAndModify to provide casting etc.
  2907. *
  2908. * @param {String} type - either "remove" or "update"
  2909. * @param {Function} callback
  2910. * @api private
  2911. */
  2912. Query.prototype._findAndModify = function(type, callback) {
  2913. if (typeof callback !== 'function') {
  2914. throw new Error('Expected callback in _findAndModify');
  2915. }
  2916. const model = this.model;
  2917. const schema = model.schema;
  2918. const _this = this;
  2919. let castedDoc = this._update;
  2920. let fields;
  2921. let doValidate;
  2922. const castedQuery = castQuery(this);
  2923. if (castedQuery instanceof Error) {
  2924. return callback(castedQuery);
  2925. }
  2926. _castArrayFilters(this);
  2927. const opts = this._optionsForExec(model);
  2928. if ('strict' in opts) {
  2929. this._mongooseOptions.strict = opts.strict;
  2930. }
  2931. const isOverwriting = this.options.overwrite && !hasDollarKeys(castedDoc);
  2932. if (isOverwriting) {
  2933. castedDoc = new this.model(castedDoc, null, true);
  2934. }
  2935. if (type === 'remove') {
  2936. opts.remove = true;
  2937. } else {
  2938. if (!('new' in opts)) {
  2939. opts.new = false;
  2940. }
  2941. if (!('upsert' in opts)) {
  2942. opts.upsert = false;
  2943. }
  2944. if (opts.upsert || opts['new']) {
  2945. opts.remove = false;
  2946. }
  2947. if (isOverwriting) {
  2948. doValidate = function(callback) {
  2949. castedDoc.validate(callback);
  2950. };
  2951. } else {
  2952. castedDoc = castDoc(this, opts.overwrite);
  2953. castedDoc = setDefaultsOnInsert(this._conditions, schema, castedDoc, opts);
  2954. if (!castedDoc) {
  2955. if (opts.upsert) {
  2956. // still need to do the upsert to empty doc
  2957. const doc = utils.clone(castedQuery);
  2958. delete doc._id;
  2959. castedDoc = {$set: doc};
  2960. } else {
  2961. this.findOne(callback);
  2962. return this;
  2963. }
  2964. } else if (castedDoc instanceof Error) {
  2965. return callback(castedDoc);
  2966. } else {
  2967. // In order to make MongoDB 2.6 happy (see
  2968. // https://jira.mongodb.org/browse/SERVER-12266 and related issues)
  2969. // if we have an actual update document but $set is empty, junk the $set.
  2970. if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) {
  2971. delete castedDoc.$set;
  2972. }
  2973. }
  2974. doValidate = updateValidators(this, schema, castedDoc, opts);
  2975. }
  2976. }
  2977. this._applyPaths();
  2978. const options = this._mongooseOptions;
  2979. if (this._fields) {
  2980. fields = utils.clone(this._fields);
  2981. opts.projection = this._castFields(fields);
  2982. if (opts.projection instanceof Error) {
  2983. return callback(opts.projection);
  2984. }
  2985. }
  2986. if (opts.sort) convertSortToArray(opts);
  2987. const cb = function(err, doc, res) {
  2988. if (err) {
  2989. return callback(err);
  2990. }
  2991. _this._completeOne(doc, res, callback);
  2992. };
  2993. let _callback;
  2994. let useFindAndModify = true;
  2995. const runValidators = _getOption(this, 'runValidators', false);
  2996. const base = _this.model && _this.model.base;
  2997. const conn = get(model, 'collection.conn', {});
  2998. if ('useFindAndModify' in base.options) {
  2999. useFindAndModify = base.get('useFindAndModify');
  3000. }
  3001. if ('useFindAndModify' in conn.config) {
  3002. useFindAndModify = conn.config.useFindAndModify;
  3003. }
  3004. if ('useFindAndModify' in options) {
  3005. useFindAndModify = options.useFindAndModify;
  3006. }
  3007. if (useFindAndModify === false) {
  3008. // Bypass mquery
  3009. const collection = _this._collection.collection;
  3010. if ('new' in opts) {
  3011. opts.returnOriginal = !opts['new'];
  3012. delete opts['new'];
  3013. }
  3014. if (type === 'remove') {
  3015. collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) {
  3016. return cb(error, res ? res.value : res, res);
  3017. }));
  3018. return this;
  3019. }
  3020. // honors legacy overwrite option for backward compatibility
  3021. const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate';
  3022. if (runValidators && doValidate) {
  3023. _callback = function(error) {
  3024. if (error) {
  3025. return callback(error);
  3026. }
  3027. if (castedDoc && castedDoc.toBSON) {
  3028. castedDoc = castedDoc.toBSON();
  3029. }
  3030. collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
  3031. return cb(error, res ? res.value : res, res);
  3032. }));
  3033. };
  3034. try {
  3035. doValidate(_callback);
  3036. } catch (error) {
  3037. callback(error);
  3038. }
  3039. } else {
  3040. if (castedDoc && castedDoc.toBSON) {
  3041. castedDoc = castedDoc.toBSON();
  3042. }
  3043. collection[updateMethod](castedQuery, castedDoc, opts, _wrapThunkCallback(_this, function(error, res) {
  3044. return cb(error, res ? res.value : res, res);
  3045. }));
  3046. }
  3047. return this;
  3048. }
  3049. if (runValidators && doValidate) {
  3050. _callback = function(error) {
  3051. if (error) {
  3052. return callback(error);
  3053. }
  3054. _legacyFindAndModify.call(_this, castedQuery, castedDoc, opts, cb);
  3055. };
  3056. try {
  3057. doValidate(_callback);
  3058. } catch (error) {
  3059. callback(error);
  3060. }
  3061. } else {
  3062. _legacyFindAndModify.call(_this, castedQuery, castedDoc, opts, cb);
  3063. }
  3064. return this;
  3065. };
  3066. /*!
  3067. * ignore
  3068. */
  3069. function _completeOneLean(doc, res, opts, callback) {
  3070. if (opts.rawResult) {
  3071. return callback(null, res);
  3072. }
  3073. return callback(null, doc);
  3074. }
  3075. /*!
  3076. * ignore
  3077. */
  3078. const _legacyFindAndModify = util.deprecate(function(filter, update, opts, cb) {
  3079. if (update && update.toBSON) {
  3080. update = update.toBSON();
  3081. }
  3082. const collection = this._collection;
  3083. const sort = opts != null && Array.isArray(opts.sort) ? opts.sort : [];
  3084. const _cb = _wrapThunkCallback(this, function(error, res) {
  3085. return cb(error, res ? res.value : res, res);
  3086. });
  3087. collection.collection._findAndModify(filter, sort, update, opts, _cb);
  3088. }, 'Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the ' +
  3089. '`useFindAndModify` option set to false are deprecated. See: ' +
  3090. 'https://mongoosejs.com/docs/deprecations.html#-findandmodify-');
  3091. /*!
  3092. * Override mquery.prototype._mergeUpdate to handle mongoose objects in
  3093. * updates.
  3094. *
  3095. * @param {Object} doc
  3096. * @api private
  3097. */
  3098. Query.prototype._mergeUpdate = function(doc) {
  3099. if (!this._update) this._update = {};
  3100. if (doc instanceof Query) {
  3101. if (doc._update) {
  3102. utils.mergeClone(this._update, doc._update);
  3103. }
  3104. } else {
  3105. utils.mergeClone(this._update, doc);
  3106. }
  3107. };
  3108. /*!
  3109. * The mongodb driver 1.3.23 only supports the nested array sort
  3110. * syntax. We must convert it or sorting findAndModify will not work.
  3111. */
  3112. function convertSortToArray(opts) {
  3113. if (Array.isArray(opts.sort)) {
  3114. return;
  3115. }
  3116. if (!utils.isObject(opts.sort)) {
  3117. return;
  3118. }
  3119. const sort = [];
  3120. for (const key in opts.sort) {
  3121. if (utils.object.hasOwnProperty(opts.sort, key)) {
  3122. sort.push([key, opts.sort[key]]);
  3123. }
  3124. }
  3125. opts.sort = sort;
  3126. }
  3127. /*!
  3128. * ignore
  3129. */
  3130. function _updateThunk(op, callback) {
  3131. const schema = this.model.schema;
  3132. let doValidate;
  3133. const _this = this;
  3134. this._castConditions();
  3135. _castArrayFilters(this);
  3136. if (this.error() != null) {
  3137. callback(this.error());
  3138. return null;
  3139. }
  3140. callback = _wrapThunkCallback(this, callback);
  3141. const castedQuery = this._conditions;
  3142. let castedDoc;
  3143. const options = this._optionsForExec(this.model);
  3144. ++this._executionCount;
  3145. this._update = utils.clone(this._update, options);
  3146. const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update);
  3147. if (isOverwriting) {
  3148. if (op === 'updateOne' || op === 'updateMany') {
  3149. return callback(new MongooseError('The MongoDB server disallows ' +
  3150. 'overwriting documents using `' + op + '`. See: ' +
  3151. 'https://mongoosejs.com/docs/deprecations.html#-update-'));
  3152. }
  3153. castedDoc = new this.model(this._update, null, true);
  3154. } else {
  3155. castedDoc = castDoc(this, options.overwrite);
  3156. if (castedDoc instanceof Error) {
  3157. callback(castedDoc);
  3158. return null;
  3159. }
  3160. if (castedDoc == null || Object.keys(castedDoc).length === 0) {
  3161. callback(null, 0);
  3162. return null;
  3163. }
  3164. castedDoc = setDefaultsOnInsert(this._conditions, this.model.schema,
  3165. castedDoc, options);
  3166. }
  3167. const runValidators = _getOption(this, 'runValidators', false);
  3168. if (runValidators) {
  3169. if (isOverwriting) {
  3170. doValidate = function(callback) {
  3171. castedDoc.validate(callback);
  3172. };
  3173. } else {
  3174. doValidate = updateValidators(this, schema, castedDoc, options);
  3175. }
  3176. const _callback = function(err) {
  3177. if (err) {
  3178. return callback(err);
  3179. }
  3180. if (castedDoc.toBSON) {
  3181. castedDoc = castedDoc.toBSON();
  3182. }
  3183. _this._collection[op](castedQuery, castedDoc, options, callback);
  3184. };
  3185. try {
  3186. doValidate(_callback);
  3187. } catch (err) {
  3188. process.nextTick(function() {
  3189. callback(err);
  3190. });
  3191. }
  3192. return null;
  3193. }
  3194. if (castedDoc.toBSON) {
  3195. castedDoc = castedDoc.toBSON();
  3196. }
  3197. this._collection[op](castedQuery, castedDoc, options, callback);
  3198. return null;
  3199. }
  3200. /*!
  3201. * Internal thunk for .update()
  3202. *
  3203. * @param {Function} callback
  3204. * @see Model.update #model_Model.update
  3205. * @api private
  3206. */
  3207. Query.prototype._execUpdate = wrapThunk(function(callback) {
  3208. return _updateThunk.call(this, 'update', callback);
  3209. });
  3210. /*!
  3211. * Internal thunk for .updateMany()
  3212. *
  3213. * @param {Function} callback
  3214. * @see Model.update #model_Model.update
  3215. * @api private
  3216. */
  3217. Query.prototype._updateMany = wrapThunk(function(callback) {
  3218. return _updateThunk.call(this, 'updateMany', callback);
  3219. });
  3220. /*!
  3221. * Internal thunk for .updateOne()
  3222. *
  3223. * @param {Function} callback
  3224. * @see Model.update #model_Model.update
  3225. * @api private
  3226. */
  3227. Query.prototype._updateOne = wrapThunk(function(callback) {
  3228. return _updateThunk.call(this, 'updateOne', callback);
  3229. });
  3230. /*!
  3231. * Internal thunk for .replaceOne()
  3232. *
  3233. * @param {Function} callback
  3234. * @see Model.replaceOne #model_Model.replaceOne
  3235. * @api private
  3236. */
  3237. Query.prototype._replaceOne = wrapThunk(function(callback) {
  3238. return _updateThunk.call(this, 'replaceOne', callback);
  3239. });
  3240. /**
  3241. * Declare and/or execute this query as an update() operation.
  3242. *
  3243. * _All paths passed that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operations will become `$set` ops._
  3244. *
  3245. * This function triggers the following middleware.
  3246. *
  3247. * - `update()`
  3248. *
  3249. * ####Example
  3250. *
  3251. * Model.where({ _id: id }).update({ title: 'words' })
  3252. *
  3253. * // becomes
  3254. *
  3255. * Model.where({ _id: id }).update({ $set: { title: 'words' }})
  3256. *
  3257. * ####Valid options:
  3258. *
  3259. * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
  3260. * - `multi` (boolean) whether multiple documents should be updated (false)
  3261. * - `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.
  3262. * - `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/).
  3263. * - `strict` (boolean) overrides the `strict` option for this update
  3264. * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
  3265. * - `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.
  3266. * - `read`
  3267. * - `writeConcern`
  3268. *
  3269. * ####Note
  3270. *
  3271. * 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.
  3272. *
  3273. * ####Note
  3274. *
  3275. * 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.
  3276. *
  3277. * var q = Model.where({ _id: id });
  3278. * q.update({ $set: { name: 'bob' }}).update(); // not executed
  3279. *
  3280. * q.update({ $set: { name: 'bob' }}).exec(); // executed
  3281. *
  3282. * // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`.
  3283. * // this executes the same command as the previous example.
  3284. * q.update({ name: 'bob' }).exec();
  3285. *
  3286. * // overwriting with empty docs
  3287. * var q = Model.where({ _id: id }).setOptions({ overwrite: true })
  3288. * q.update({ }, callback); // executes
  3289. *
  3290. * // multi update with overwrite to empty doc
  3291. * var q = Model.where({ _id: id });
  3292. * q.setOptions({ multi: true, overwrite: true })
  3293. * q.update({ });
  3294. * q.update(callback); // executed
  3295. *
  3296. * // multi updates
  3297. * Model.where()
  3298. * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
  3299. *
  3300. * // more multi updates
  3301. * Model.where()
  3302. * .setOptions({ multi: true })
  3303. * .update({ $set: { arr: [] }}, callback)
  3304. *
  3305. * // single update by default
  3306. * Model.where({ email: 'address@example.com' })
  3307. * .update({ $inc: { counter: 1 }}, callback)
  3308. *
  3309. * API summary
  3310. *
  3311. * update(criteria, doc, options, cb) // executes
  3312. * update(criteria, doc, options)
  3313. * update(criteria, doc, cb) // executes
  3314. * update(criteria, doc)
  3315. * update(doc, cb) // executes
  3316. * update(doc)
  3317. * update(cb) // executes
  3318. * update(true) // executes
  3319. * update()
  3320. *
  3321. * @param {Object} [criteria]
  3322. * @param {Object} [doc] the update command
  3323. * @param {Object} [options]
  3324. * @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.
  3325. * @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.
  3326. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3327. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3328. * @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)
  3329. * @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.
  3330. * @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.
  3331. * @param {Function} [callback] params are (error, writeOpResult)
  3332. * @return {Query} this
  3333. * @see Model.update #model_Model.update
  3334. * @see Query docs https://mongoosejs.com/docs/queries.html
  3335. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3336. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3337. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3338. * @api public
  3339. */
  3340. Query.prototype.update = function(conditions, doc, options, callback) {
  3341. if (typeof options === 'function') {
  3342. // .update(conditions, doc, callback)
  3343. callback = options;
  3344. options = null;
  3345. } else if (typeof doc === 'function') {
  3346. // .update(doc, callback);
  3347. callback = doc;
  3348. doc = conditions;
  3349. conditions = {};
  3350. options = null;
  3351. } else if (typeof conditions === 'function') {
  3352. // .update(callback)
  3353. callback = conditions;
  3354. conditions = undefined;
  3355. doc = undefined;
  3356. options = undefined;
  3357. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3358. // .update(doc)
  3359. doc = conditions;
  3360. conditions = undefined;
  3361. options = undefined;
  3362. callback = undefined;
  3363. }
  3364. return _update(this, 'update', conditions, doc, options, callback);
  3365. };
  3366. /**
  3367. * Declare and/or execute this query as an updateMany() operation. Same as
  3368. * `update()`, except MongoDB will update _all_ documents that match
  3369. * `criteria` (as opposed to just the first one) regardless of the value of
  3370. * the `multi` option.
  3371. *
  3372. * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
  3373. * and `post('updateMany')` instead.
  3374. *
  3375. * ####Example:
  3376. * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
  3377. * res.n; // Number of documents matched
  3378. * res.nModified; // Number of documents modified
  3379. *
  3380. * This function triggers the following middleware.
  3381. *
  3382. * - `updateMany()`
  3383. *
  3384. * @param {Object} [criteria]
  3385. * @param {Object} [doc] the update command
  3386. * @param {Object} [options]
  3387. * @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.
  3388. * @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.
  3389. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3390. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3391. * @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)
  3392. * @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.
  3393. * @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.
  3394. * @param {Function} [callback] params are (error, writeOpResult)
  3395. * @return {Query} this
  3396. * @see Model.update #model_Model.update
  3397. * @see Query docs https://mongoosejs.com/docs/queries.html
  3398. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3399. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3400. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3401. * @api public
  3402. */
  3403. Query.prototype.updateMany = function(conditions, doc, options, callback) {
  3404. if (typeof options === 'function') {
  3405. // .update(conditions, doc, callback)
  3406. callback = options;
  3407. options = null;
  3408. } else if (typeof doc === 'function') {
  3409. // .update(doc, callback);
  3410. callback = doc;
  3411. doc = conditions;
  3412. conditions = {};
  3413. options = null;
  3414. } else if (typeof conditions === 'function') {
  3415. // .update(callback)
  3416. callback = conditions;
  3417. conditions = undefined;
  3418. doc = undefined;
  3419. options = undefined;
  3420. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3421. // .update(doc)
  3422. doc = conditions;
  3423. conditions = undefined;
  3424. options = undefined;
  3425. callback = undefined;
  3426. }
  3427. return _update(this, 'updateMany', conditions, doc, options, callback);
  3428. };
  3429. /**
  3430. * Declare and/or execute this query as an updateOne() operation. Same as
  3431. * `update()`, except it does not support the `multi` or `overwrite` options.
  3432. *
  3433. * - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option.
  3434. * - 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`.
  3435. *
  3436. * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')`
  3437. * and `post('updateOne')` instead.
  3438. *
  3439. * ####Example:
  3440. * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
  3441. * res.n; // Number of documents matched
  3442. * res.nModified; // Number of documents modified
  3443. *
  3444. * This function triggers the following middleware.
  3445. *
  3446. * - `updateOne()`
  3447. *
  3448. * @param {Object} [criteria]
  3449. * @param {Object} [doc] the update command
  3450. * @param {Object} [options]
  3451. * @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.
  3452. * @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.
  3453. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3454. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3455. * @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)
  3456. * @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.
  3457. * @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.
  3458. * @param {Function} [callback] params are (error, writeOpResult)
  3459. * @return {Query} this
  3460. * @see Model.update #model_Model.update
  3461. * @see Query docs https://mongoosejs.com/docs/queries.html
  3462. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3463. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3464. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3465. * @api public
  3466. */
  3467. Query.prototype.updateOne = function(conditions, doc, options, callback) {
  3468. if (typeof options === 'function') {
  3469. // .update(conditions, doc, callback)
  3470. callback = options;
  3471. options = null;
  3472. } else if (typeof doc === 'function') {
  3473. // .update(doc, callback);
  3474. callback = doc;
  3475. doc = conditions;
  3476. conditions = {};
  3477. options = null;
  3478. } else if (typeof conditions === 'function') {
  3479. // .update(callback)
  3480. callback = conditions;
  3481. conditions = undefined;
  3482. doc = undefined;
  3483. options = undefined;
  3484. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3485. // .update(doc)
  3486. doc = conditions;
  3487. conditions = undefined;
  3488. options = undefined;
  3489. callback = undefined;
  3490. }
  3491. return _update(this, 'updateOne', conditions, doc, options, callback);
  3492. };
  3493. /**
  3494. * Declare and/or execute this query as a replaceOne() operation. Same as
  3495. * `update()`, except MongoDB will replace the existing document and will
  3496. * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
  3497. *
  3498. * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')`
  3499. * and `post('replaceOne')` instead.
  3500. *
  3501. * ####Example:
  3502. * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
  3503. * res.n; // Number of documents matched
  3504. * res.nModified; // Number of documents modified
  3505. *
  3506. * This function triggers the following middleware.
  3507. *
  3508. * - `replaceOne()`
  3509. *
  3510. * @param {Object} [criteria]
  3511. * @param {Object} [doc] the update command
  3512. * @param {Object} [options]
  3513. * @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.
  3514. * @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.
  3515. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3516. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3517. * @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)
  3518. * @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.
  3519. * @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.
  3520. * @param {Function} [callback] params are (error, writeOpResult)
  3521. * @return {Query} this
  3522. * @see Model.update #model_Model.update
  3523. * @see Query docs https://mongoosejs.com/docs/queries.html
  3524. * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/
  3525. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3526. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3527. * @api public
  3528. */
  3529. Query.prototype.replaceOne = function(conditions, doc, options, callback) {
  3530. if (typeof options === 'function') {
  3531. // .update(conditions, doc, callback)
  3532. callback = options;
  3533. options = null;
  3534. } else if (typeof doc === 'function') {
  3535. // .update(doc, callback);
  3536. callback = doc;
  3537. doc = conditions;
  3538. conditions = {};
  3539. options = null;
  3540. } else if (typeof conditions === 'function') {
  3541. // .update(callback)
  3542. callback = conditions;
  3543. conditions = undefined;
  3544. doc = undefined;
  3545. options = undefined;
  3546. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
  3547. // .update(doc)
  3548. doc = conditions;
  3549. conditions = undefined;
  3550. options = undefined;
  3551. callback = undefined;
  3552. }
  3553. this.setOptions({ overwrite: true });
  3554. return _update(this, 'replaceOne', conditions, doc, options, callback);
  3555. };
  3556. /*!
  3557. * Internal helper for update, updateMany, updateOne, replaceOne
  3558. */
  3559. function _update(query, op, filter, doc, options, callback) {
  3560. // make sure we don't send in the whole Document to merge()
  3561. query.op = op;
  3562. filter = utils.toObject(filter);
  3563. doc = doc || {};
  3564. const oldCb = callback;
  3565. if (oldCb) {
  3566. if (typeof oldCb === 'function') {
  3567. callback = function(error, result) {
  3568. oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0});
  3569. };
  3570. } else {
  3571. throw new Error('Invalid callback() argument.');
  3572. }
  3573. }
  3574. // strict is an option used in the update checking, make sure it gets set
  3575. if (options != null) {
  3576. if ('strict' in options) {
  3577. query._mongooseOptions.strict = options.strict;
  3578. }
  3579. }
  3580. if (!(filter instanceof Query) &&
  3581. filter != null &&
  3582. filter.toString() !== '[object Object]') {
  3583. query.error(new ObjectParameterError(filter, 'filter', op));
  3584. } else {
  3585. query.merge(filter);
  3586. }
  3587. if (utils.isObject(options)) {
  3588. query.setOptions(options);
  3589. }
  3590. query._mergeUpdate(doc);
  3591. // Hooks
  3592. if (callback) {
  3593. if (op === 'update') {
  3594. query._execUpdate(callback);
  3595. return query;
  3596. }
  3597. query['_' + op](callback);
  3598. return query;
  3599. }
  3600. return Query.base[op].call(query, filter, doc, options, callback);
  3601. }
  3602. /**
  3603. * Runs a function `fn` and treats the return value of `fn` as the new value
  3604. * for the query to resolve to.
  3605. *
  3606. * Any functions you pass to `map()` will run **after** any post hooks.
  3607. *
  3608. * ####Example:
  3609. *
  3610. * const res = await MyModel.findOne().map(res => {
  3611. * // Sets a `loadedAt` property on the doc that tells you the time the
  3612. * // document was loaded.
  3613. * return res == null ?
  3614. * res :
  3615. * Object.assign(res, { loadedAt: new Date() });
  3616. * });
  3617. *
  3618. * @method map
  3619. * @memberOf Query
  3620. * @instance
  3621. * @param {Function} fn function to run to transform the query result
  3622. * @return {Query} this
  3623. */
  3624. Query.prototype.map = function(fn) {
  3625. this._transforms.push(fn);
  3626. return this;
  3627. };
  3628. /**
  3629. * Make this query throw an error if no documents match the given `filter`.
  3630. * This is handy for integrating with async/await, because `orFail()` saves you
  3631. * an extra `if` statement to check if no document was found.
  3632. *
  3633. * ####Example:
  3634. *
  3635. * // Throws if no doc returned
  3636. * await Model.findOne({ foo: 'bar' }).orFail();
  3637. *
  3638. * // Throws if no document was updated
  3639. * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
  3640. *
  3641. * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
  3642. * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
  3643. *
  3644. * // Throws "Not found" error if no document was found
  3645. * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
  3646. * orFail(() => Error('Not found'));
  3647. *
  3648. * @method orFail
  3649. * @memberOf Query
  3650. * @instance
  3651. * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError`
  3652. * @return {Query} this
  3653. */
  3654. Query.prototype.orFail = function(err) {
  3655. this.map(res => {
  3656. switch (this.op) {
  3657. case 'find':
  3658. if (res.length === 0) {
  3659. throw _orFailError(err, this);
  3660. }
  3661. break;
  3662. case 'findOne':
  3663. if (res == null) {
  3664. throw _orFailError(err, this);
  3665. }
  3666. break;
  3667. case 'update':
  3668. case 'updateMany':
  3669. case 'updateOne':
  3670. if (get(res, 'result.nModified') === 0) {
  3671. throw _orFailError(err, this);
  3672. }
  3673. break;
  3674. case 'findOneAndDelete':
  3675. if (get(res, 'lastErrorObject.n') === 0) {
  3676. throw _orFailError(err, this);
  3677. }
  3678. break;
  3679. case 'findOneAndUpdate':
  3680. if (get(res, 'lastErrorObject.updatedExisting') === false) {
  3681. throw _orFailError(err, this);
  3682. }
  3683. break;
  3684. case 'deleteMany':
  3685. case 'deleteOne':
  3686. case 'remove':
  3687. if (res.n === 0) {
  3688. throw _orFailError(err, this);
  3689. }
  3690. break;
  3691. default:
  3692. break;
  3693. }
  3694. return res;
  3695. });
  3696. return this;
  3697. };
  3698. /*!
  3699. * Get the error to throw for `orFail()`
  3700. */
  3701. function _orFailError(err, query) {
  3702. if (typeof err === 'function') {
  3703. err = err.call(query);
  3704. }
  3705. if (err == null) {
  3706. err = new DocumentNotFoundError(query.getQuery());
  3707. }
  3708. return err;
  3709. }
  3710. /**
  3711. * Executes the query
  3712. *
  3713. * ####Examples:
  3714. *
  3715. * var promise = query.exec();
  3716. * var promise = query.exec('update');
  3717. *
  3718. * query.exec(callback);
  3719. * query.exec('find', callback);
  3720. *
  3721. * @param {String|Function} [operation]
  3722. * @param {Function} [callback] optional params depend on the function being called
  3723. * @return {Promise}
  3724. * @api public
  3725. */
  3726. Query.prototype.exec = function exec(op, callback) {
  3727. const _this = this;
  3728. if (typeof op === 'function') {
  3729. callback = op;
  3730. op = null;
  3731. } else if (typeof op === 'string') {
  3732. this.op = op;
  3733. }
  3734. if (callback != null) {
  3735. callback = this.model.$wrapCallback(callback);
  3736. }
  3737. return utils.promiseOrCallback(callback, (cb) => {
  3738. if (!_this.op) {
  3739. cb();
  3740. return;
  3741. }
  3742. this._hooks.execPre('exec', this, [], (error) => {
  3743. if (error) {
  3744. return cb(error);
  3745. }
  3746. this[this.op].call(this, (error, res) => {
  3747. if (error) {
  3748. return cb(error);
  3749. }
  3750. this._hooks.execPost('exec', this, [], {}, (error) => {
  3751. if (error) {
  3752. return cb(error);
  3753. }
  3754. cb(null, res);
  3755. });
  3756. });
  3757. });
  3758. }, this.model.events);
  3759. };
  3760. /*!
  3761. * ignore
  3762. */
  3763. function _wrapThunkCallback(query, cb) {
  3764. return function(error, res) {
  3765. if (error != null) {
  3766. return cb(error);
  3767. }
  3768. for (const fn of query._transforms) {
  3769. try {
  3770. res = fn(res);
  3771. } catch (error) {
  3772. return cb(error);
  3773. }
  3774. }
  3775. return cb(null, res);
  3776. };
  3777. }
  3778. /**
  3779. * Executes the query returning a `Promise` which will be
  3780. * resolved with either the doc(s) or rejected with the error.
  3781. *
  3782. * @param {Function} [resolve]
  3783. * @param {Function} [reject]
  3784. * @return {Promise}
  3785. * @api public
  3786. */
  3787. Query.prototype.then = function(resolve, reject) {
  3788. return this.exec().then(resolve, reject);
  3789. };
  3790. /**
  3791. * Executes the query returning a `Promise` which will be
  3792. * resolved with either the doc(s) or rejected with the error.
  3793. * Like `.then()`, but only takes a rejection handler.
  3794. *
  3795. * @param {Function} [reject]
  3796. * @return {Promise}
  3797. * @api public
  3798. */
  3799. Query.prototype.catch = function(reject) {
  3800. return this.exec().then(null, reject);
  3801. };
  3802. /*!
  3803. * ignore
  3804. */
  3805. Query.prototype._pre = function(fn) {
  3806. this._hooks.pre('exec', fn);
  3807. return this;
  3808. };
  3809. /*!
  3810. * ignore
  3811. */
  3812. Query.prototype._post = function(fn) {
  3813. this._hooks.post('exec', fn);
  3814. return this;
  3815. };
  3816. /*!
  3817. * Casts obj for an update command.
  3818. *
  3819. * @param {Object} obj
  3820. * @return {Object} obj after casting its values
  3821. * @api private
  3822. */
  3823. Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
  3824. let strict;
  3825. if ('strict' in this._mongooseOptions) {
  3826. strict = this._mongooseOptions.strict;
  3827. } else if (this.schema && this.schema.options) {
  3828. strict = this.schema.options.strict;
  3829. } else {
  3830. strict = true;
  3831. }
  3832. let omitUndefined = false;
  3833. if ('omitUndefined' in this._mongooseOptions) {
  3834. omitUndefined = this._mongooseOptions.omitUndefined;
  3835. }
  3836. let useNestedStrict;
  3837. if ('useNestedStrict' in this.options) {
  3838. useNestedStrict = this.options.useNestedStrict;
  3839. }
  3840. return castUpdate(this.schema, obj, {
  3841. overwrite: overwrite,
  3842. strict: strict,
  3843. omitUndefined,
  3844. useNestedStrict: useNestedStrict
  3845. }, this, this._conditions);
  3846. };
  3847. /*!
  3848. * castQuery
  3849. * @api private
  3850. */
  3851. function castQuery(query) {
  3852. try {
  3853. return query.cast(query.model);
  3854. } catch (err) {
  3855. return err;
  3856. }
  3857. }
  3858. /*!
  3859. * castDoc
  3860. * @api private
  3861. */
  3862. function castDoc(query, overwrite) {
  3863. try {
  3864. return query._castUpdate(query._update, overwrite);
  3865. } catch (err) {
  3866. return err;
  3867. }
  3868. }
  3869. /**
  3870. * Specifies paths which should be populated with other documents.
  3871. *
  3872. * ####Example:
  3873. *
  3874. * Kitten.findOne().populate('owner').exec(function (err, kitten) {
  3875. * console.log(kitten.owner.name) // Max
  3876. * })
  3877. *
  3878. * Kitten.find().populate({
  3879. * path: 'owner',
  3880. * select: 'name',
  3881. * match: { color: 'black' },
  3882. * options: { sort: { name: -1 } }
  3883. * }).exec(function (err, kittens) {
  3884. * console.log(kittens[0].owner.name) // Zoopa
  3885. * })
  3886. *
  3887. * // alternatively
  3888. * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
  3889. * console.log(kittens[0].owner.name) // Zoopa
  3890. * })
  3891. *
  3892. * Paths are populated after the query executes and a response is received. A
  3893. * separate query is then executed for each path specified for population. After
  3894. * a response for each query has also been returned, the results are passed to
  3895. * the callback.
  3896. *
  3897. * @param {Object|String} path either the path to populate or an object specifying all parameters
  3898. * @param {Object|String} [select] Field selection for the population query
  3899. * @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.
  3900. * @param {Object} [match] Conditions for the population query
  3901. * @param {Object} [options] Options for the population query (sort, etc)
  3902. * @param {String} [options.path=null] The path to populate.
  3903. * @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.
  3904. * @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).
  3905. * @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.
  3906. * @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.
  3907. * @see population ./populate.html
  3908. * @see Query#select #query_Query-select
  3909. * @see Model.populate #model_Model.populate
  3910. * @return {Query} this
  3911. * @api public
  3912. */
  3913. Query.prototype.populate = function() {
  3914. if (arguments.length === 0) {
  3915. return this;
  3916. }
  3917. const res = utils.populate.apply(null, arguments);
  3918. // Propagate readConcern and readPreference and lean from parent query,
  3919. // unless one already specified
  3920. if (this.options != null) {
  3921. const readConcern = this.options.readConcern;
  3922. const readPref = this.options.readPreference;
  3923. for (let i = 0; i < res.length; ++i) {
  3924. if (readConcern != null && get(res[i], 'options.readConcern') == null) {
  3925. res[i].options = res[i].options || {};
  3926. res[i].options.readConcern = readConcern;
  3927. }
  3928. if (readPref != null && get(res[i], 'options.readPreference') == null) {
  3929. res[i].options = res[i].options || {};
  3930. res[i].options.readPreference = readPref;
  3931. }
  3932. }
  3933. }
  3934. const opts = this._mongooseOptions;
  3935. if (opts.lean != null) {
  3936. const lean = opts.lean;
  3937. for (let i = 0; i < res.length; ++i) {
  3938. if (get(res[i], 'options.lean') == null) {
  3939. res[i].options = res[i].options || {};
  3940. res[i].options.lean = lean;
  3941. }
  3942. }
  3943. }
  3944. if (!utils.isObject(opts.populate)) {
  3945. opts.populate = {};
  3946. }
  3947. const pop = opts.populate;
  3948. for (let i = 0; i < res.length; ++i) {
  3949. const path = res[i].path;
  3950. if (pop[path] && pop[path].populate && res[i].populate) {
  3951. res[i].populate = pop[path].populate.concat(res[i].populate);
  3952. }
  3953. pop[res[i].path] = res[i];
  3954. }
  3955. return this;
  3956. };
  3957. /**
  3958. * Gets a list of paths to be populated by this query
  3959. *
  3960. * ####Example:
  3961. * bookSchema.pre('findOne', function() {
  3962. * let keys = this.getPopulatedPaths(); // ['author']
  3963. * });
  3964. * ...
  3965. * Book.findOne({}).populate('author');
  3966. *
  3967. * ####Example:
  3968. * // Deep populate
  3969. * const q = L1.find().populate({
  3970. * path: 'level2',
  3971. * populate: { path: 'level3' }
  3972. * });
  3973. * q.getPopulatedPaths(); // ['level2', 'level2.level3']
  3974. *
  3975. * @return {Array} an array of strings representing populated paths
  3976. * @api public
  3977. */
  3978. Query.prototype.getPopulatedPaths = function getPopulatedPaths() {
  3979. const obj = this._mongooseOptions.populate || {};
  3980. const ret = Object.keys(obj);
  3981. for (const path of Object.keys(obj)) {
  3982. const pop = obj[path];
  3983. if (!Array.isArray(pop.populate)) {
  3984. continue;
  3985. }
  3986. _getPopulatedPaths(ret, pop.populate, path + '.');
  3987. }
  3988. return ret;
  3989. };
  3990. /*!
  3991. * ignore
  3992. */
  3993. function _getPopulatedPaths(list, arr, prefix) {
  3994. for (const pop of arr) {
  3995. list.push(prefix + pop.path);
  3996. if (!Array.isArray(pop.populate)) {
  3997. continue;
  3998. }
  3999. _getPopulatedPaths(list, pop.populate, prefix + pop.path + '.');
  4000. }
  4001. }
  4002. /**
  4003. * Casts this query to the schema of `model`
  4004. *
  4005. * ####Note
  4006. *
  4007. * If `obj` is present, it is cast instead of this query.
  4008. *
  4009. * @param {Model} [model] the model to cast to. If not set, defaults to `this.model`
  4010. * @param {Object} [obj]
  4011. * @return {Object}
  4012. * @api public
  4013. */
  4014. Query.prototype.cast = function(model, obj) {
  4015. obj || (obj = this._conditions);
  4016. model = model || this.model;
  4017. try {
  4018. return cast(model.schema, obj, {
  4019. upsert: this.options && this.options.upsert,
  4020. strict: (this.options && 'strict' in this.options) ?
  4021. this.options.strict :
  4022. get(model, 'schema.options.strict', null),
  4023. strictQuery: (this.options && this.options.strictQuery) ||
  4024. get(model, 'schema.options.strictQuery', null)
  4025. }, this);
  4026. } catch (err) {
  4027. // CastError, assign model
  4028. if (typeof err.setModel === 'function') {
  4029. err.setModel(model);
  4030. }
  4031. throw err;
  4032. }
  4033. };
  4034. /**
  4035. * Casts selected field arguments for field selection with mongo 2.2
  4036. *
  4037. * query.select({ ids: { $elemMatch: { $in: [hexString] }})
  4038. *
  4039. * @param {Object} fields
  4040. * @see https://github.com/Automattic/mongoose/issues/1091
  4041. * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/
  4042. * @api private
  4043. */
  4044. Query.prototype._castFields = function _castFields(fields) {
  4045. let selected,
  4046. elemMatchKeys,
  4047. keys,
  4048. key,
  4049. out,
  4050. i;
  4051. if (fields) {
  4052. keys = Object.keys(fields);
  4053. elemMatchKeys = [];
  4054. i = keys.length;
  4055. // collect $elemMatch args
  4056. while (i--) {
  4057. key = keys[i];
  4058. if (fields[key].$elemMatch) {
  4059. selected || (selected = {});
  4060. selected[key] = fields[key];
  4061. elemMatchKeys.push(key);
  4062. }
  4063. }
  4064. }
  4065. if (selected) {
  4066. // they passed $elemMatch, cast em
  4067. try {
  4068. out = this.cast(this.model, selected);
  4069. } catch (err) {
  4070. return err;
  4071. }
  4072. // apply the casted field args
  4073. i = elemMatchKeys.length;
  4074. while (i--) {
  4075. key = elemMatchKeys[i];
  4076. fields[key] = out[key];
  4077. }
  4078. }
  4079. return fields;
  4080. };
  4081. /**
  4082. * Applies schematype selected options to this query.
  4083. * @api private
  4084. */
  4085. Query.prototype._applyPaths = function applyPaths() {
  4086. this._fields = this._fields || {};
  4087. helpers.applyPaths(this._fields, this.model.schema);
  4088. let _selectPopulatedPaths = true;
  4089. if ('selectPopulatedPaths' in this.model.base.options) {
  4090. _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths;
  4091. }
  4092. if ('selectPopulatedPaths' in this.model.schema.options) {
  4093. _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths;
  4094. }
  4095. if (_selectPopulatedPaths) {
  4096. selectPopulatedFields(this);
  4097. }
  4098. };
  4099. /**
  4100. * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
  4101. * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
  4102. *
  4103. * The `.cursor()` function triggers pre find hooks, but **not** post find hooks.
  4104. *
  4105. * ####Example
  4106. *
  4107. * // There are 2 ways to use a cursor. First, as a stream:
  4108. * Thing.
  4109. * find({ name: /^hello/ }).
  4110. * cursor().
  4111. * on('data', function(doc) { console.log(doc); }).
  4112. * on('end', function() { console.log('Done!'); });
  4113. *
  4114. * // Or you can use `.next()` to manually get the next doc in the stream.
  4115. * // `.next()` returns a promise, so you can use promises or callbacks.
  4116. * var cursor = Thing.find({ name: /^hello/ }).cursor();
  4117. * cursor.next(function(error, doc) {
  4118. * console.log(doc);
  4119. * });
  4120. *
  4121. * // Because `.next()` returns a promise, you can use co
  4122. * // to easily iterate through all documents without loading them
  4123. * // all into memory.
  4124. * co(function*() {
  4125. * const cursor = Thing.find({ name: /^hello/ }).cursor();
  4126. * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
  4127. * console.log(doc);
  4128. * }
  4129. * });
  4130. *
  4131. * ####Valid options
  4132. *
  4133. * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`.
  4134. *
  4135. * @return {QueryCursor}
  4136. * @param {Object} [options]
  4137. * @see QueryCursor
  4138. * @api public
  4139. */
  4140. Query.prototype.cursor = function cursor(opts) {
  4141. this._applyPaths();
  4142. this._fields = this._castFields(this._fields);
  4143. this.setOptions({ projection: this._fieldsForExec() });
  4144. if (opts) {
  4145. this.setOptions(opts);
  4146. }
  4147. const options = Object.assign({}, this.options, {
  4148. projection: this.projection()
  4149. });
  4150. try {
  4151. this.cast(this.model);
  4152. } catch (err) {
  4153. return (new QueryCursor(this, options))._markError(err);
  4154. }
  4155. return new QueryCursor(this, options);
  4156. };
  4157. // the rest of these are basically to support older Mongoose syntax with mquery
  4158. /**
  4159. * _DEPRECATED_ Alias of `maxScan`
  4160. *
  4161. * @deprecated
  4162. * @see maxScan #query_Query-maxScan
  4163. * @method maxscan
  4164. * @memberOf Query
  4165. * @instance
  4166. */
  4167. Query.prototype.maxscan = Query.base.maxScan;
  4168. /**
  4169. * Sets the tailable option (for use with capped collections).
  4170. *
  4171. * ####Example
  4172. *
  4173. * query.tailable() // true
  4174. * query.tailable(true)
  4175. * query.tailable(false)
  4176. *
  4177. * ####Note
  4178. *
  4179. * Cannot be used with `distinct()`
  4180. *
  4181. * @param {Boolean} bool defaults to true
  4182. * @param {Object} [opts] options to set
  4183. * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up
  4184. * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying
  4185. * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/
  4186. * @api public
  4187. */
  4188. Query.prototype.tailable = function(val, opts) {
  4189. // we need to support the tailable({ awaitdata : true }) as well as the
  4190. // tailable(true, {awaitdata :true}) syntax that mquery does not support
  4191. if (val && val.constructor.name === 'Object') {
  4192. opts = val;
  4193. val = true;
  4194. }
  4195. if (val === undefined) {
  4196. val = true;
  4197. }
  4198. if (opts && typeof opts === 'object') {
  4199. for (const key in opts) {
  4200. if (key === 'awaitdata') {
  4201. // For backwards compatibility
  4202. this.options[key] = !!opts[key];
  4203. } else {
  4204. this.options[key] = opts[key];
  4205. }
  4206. }
  4207. }
  4208. return Query.base.tailable.call(this, val);
  4209. };
  4210. /**
  4211. * Declares an intersects query for `geometry()`.
  4212. *
  4213. * ####Example
  4214. *
  4215. * query.where('path').intersects().geometry({
  4216. * type: 'LineString'
  4217. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  4218. * })
  4219. *
  4220. * query.where('path').intersects({
  4221. * type: 'LineString'
  4222. * , coordinates: [[180.0, 11.0], [180, 9.0]]
  4223. * })
  4224. *
  4225. * ####NOTE:
  4226. *
  4227. * **MUST** be used after `where()`.
  4228. *
  4229. * ####NOTE:
  4230. *
  4231. * 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).
  4232. *
  4233. * @method intersects
  4234. * @memberOf Query
  4235. * @instance
  4236. * @param {Object} [arg]
  4237. * @return {Query} this
  4238. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  4239. * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/
  4240. * @api public
  4241. */
  4242. /**
  4243. * Specifies a `$geometry` condition
  4244. *
  4245. * ####Example
  4246. *
  4247. * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
  4248. * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
  4249. *
  4250. * // or
  4251. * var polyB = [[ 0, 0 ], [ 1, 1 ]]
  4252. * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
  4253. *
  4254. * // or
  4255. * var polyC = [ 0, 0 ]
  4256. * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
  4257. *
  4258. * // or
  4259. * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
  4260. *
  4261. * The argument is assigned to the most recent path passed to `where()`.
  4262. *
  4263. * ####NOTE:
  4264. *
  4265. * `geometry()` **must** come after either `intersects()` or `within()`.
  4266. *
  4267. * The `object` argument must contain `type` and `coordinates` properties.
  4268. * - type {String}
  4269. * - coordinates {Array}
  4270. *
  4271. * @method geometry
  4272. * @memberOf Query
  4273. * @instance
  4274. * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
  4275. * @return {Query} this
  4276. * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/
  4277. * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
  4278. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4279. * @api public
  4280. */
  4281. /**
  4282. * Specifies a `$near` or `$nearSphere` condition
  4283. *
  4284. * These operators return documents sorted by distance.
  4285. *
  4286. * ####Example
  4287. *
  4288. * query.where('loc').near({ center: [10, 10] });
  4289. * query.where('loc').near({ center: [10, 10], maxDistance: 5 });
  4290. * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
  4291. * query.near('loc', { center: [10, 10], maxDistance: 5 });
  4292. *
  4293. * @method near
  4294. * @memberOf Query
  4295. * @instance
  4296. * @param {String} [path]
  4297. * @param {Object} val
  4298. * @return {Query} this
  4299. * @see $near http://docs.mongodb.org/manual/reference/operator/near/
  4300. * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
  4301. * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
  4302. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4303. * @api public
  4304. */
  4305. /*!
  4306. * Overwriting mquery is needed to support a couple different near() forms found in older
  4307. * versions of mongoose
  4308. * near([1,1])
  4309. * near(1,1)
  4310. * near(field, [1,2])
  4311. * near(field, 1, 2)
  4312. * In addition to all of the normal forms supported by mquery
  4313. */
  4314. Query.prototype.near = function() {
  4315. const params = [];
  4316. const sphere = this._mongooseOptions.nearSphere;
  4317. // TODO refactor
  4318. if (arguments.length === 1) {
  4319. if (Array.isArray(arguments[0])) {
  4320. params.push({center: arguments[0], spherical: sphere});
  4321. } else if (typeof arguments[0] === 'string') {
  4322. // just passing a path
  4323. params.push(arguments[0]);
  4324. } else if (utils.isObject(arguments[0])) {
  4325. if (typeof arguments[0].spherical !== 'boolean') {
  4326. arguments[0].spherical = sphere;
  4327. }
  4328. params.push(arguments[0]);
  4329. } else {
  4330. throw new TypeError('invalid argument');
  4331. }
  4332. } else if (arguments.length === 2) {
  4333. if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
  4334. params.push({center: [arguments[0], arguments[1]], spherical: sphere});
  4335. } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) {
  4336. params.push(arguments[0]);
  4337. params.push({center: arguments[1], spherical: sphere});
  4338. } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) {
  4339. params.push(arguments[0]);
  4340. if (typeof arguments[1].spherical !== 'boolean') {
  4341. arguments[1].spherical = sphere;
  4342. }
  4343. params.push(arguments[1]);
  4344. } else {
  4345. throw new TypeError('invalid argument');
  4346. }
  4347. } else if (arguments.length === 3) {
  4348. if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number'
  4349. && typeof arguments[2] === 'number') {
  4350. params.push(arguments[0]);
  4351. params.push({center: [arguments[1], arguments[2]], spherical: sphere});
  4352. } else {
  4353. throw new TypeError('invalid argument');
  4354. }
  4355. } else {
  4356. throw new TypeError('invalid argument');
  4357. }
  4358. return Query.base.near.apply(this, params);
  4359. };
  4360. /**
  4361. * _DEPRECATED_ Specifies a `$nearSphere` condition
  4362. *
  4363. * ####Example
  4364. *
  4365. * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
  4366. *
  4367. * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`.
  4368. *
  4369. * ####Example
  4370. *
  4371. * query.where('loc').near({ center: [10, 10], spherical: true });
  4372. *
  4373. * @deprecated
  4374. * @see near() #query_Query-near
  4375. * @see $near http://docs.mongodb.org/manual/reference/operator/near/
  4376. * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/
  4377. * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/
  4378. */
  4379. Query.prototype.nearSphere = function() {
  4380. this._mongooseOptions.nearSphere = true;
  4381. this.near.apply(this, arguments);
  4382. return this;
  4383. };
  4384. /**
  4385. * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators)
  4386. * This function *only* works for `find()` queries.
  4387. * You do not need to call this function explicitly, the JavaScript runtime
  4388. * will call it for you.
  4389. *
  4390. * ####Example
  4391. *
  4392. * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
  4393. * console.log(doc.name);
  4394. * }
  4395. *
  4396. * Node.js 10.x supports async iterators natively without any flags. You can
  4397. * 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).
  4398. *
  4399. * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If
  4400. * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
  4401. * support async iterators.
  4402. *
  4403. * @method Symbol.asyncIterator
  4404. * @memberOf Query
  4405. * @instance
  4406. * @api public
  4407. */
  4408. if (Symbol.asyncIterator != null) {
  4409. Query.prototype[Symbol.asyncIterator] = function() {
  4410. return this.cursor().transformNull().map(doc => {
  4411. return doc == null ? { done: true } : { value: doc, done: false };
  4412. });
  4413. };
  4414. }
  4415. /**
  4416. * Specifies a `$polygon` condition
  4417. *
  4418. * ####Example
  4419. *
  4420. * query.where('loc').within().polygon([10,20], [13, 25], [7,15])
  4421. * query.polygon('loc', [10,20], [13, 25], [7,15])
  4422. *
  4423. * @method polygon
  4424. * @memberOf Query
  4425. * @instance
  4426. * @param {String|Array} [path]
  4427. * @param {Array|Object} [coordinatePairs...]
  4428. * @return {Query} this
  4429. * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/
  4430. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4431. * @api public
  4432. */
  4433. /**
  4434. * Specifies a `$box` condition
  4435. *
  4436. * ####Example
  4437. *
  4438. * var lowerLeft = [40.73083, -73.99756]
  4439. * var upperRight= [40.741404, -73.988135]
  4440. *
  4441. * query.where('loc').within().box(lowerLeft, upperRight)
  4442. * query.box({ ll : lowerLeft, ur : upperRight })
  4443. *
  4444. * @method box
  4445. * @memberOf Query
  4446. * @instance
  4447. * @see $box http://docs.mongodb.org/manual/reference/operator/box/
  4448. * @see within() Query#within #query_Query-within
  4449. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4450. * @param {Object} val
  4451. * @param [Array] Upper Right Coords
  4452. * @return {Query} this
  4453. * @api public
  4454. */
  4455. /*!
  4456. * this is needed to support the mongoose syntax of:
  4457. * box(field, { ll : [x,y], ur : [x2,y2] })
  4458. * box({ ll : [x,y], ur : [x2,y2] })
  4459. */
  4460. Query.prototype.box = function(ll, ur) {
  4461. if (!Array.isArray(ll) && utils.isObject(ll)) {
  4462. ur = ll.ur;
  4463. ll = ll.ll;
  4464. }
  4465. return Query.base.box.call(this, ll, ur);
  4466. };
  4467. /**
  4468. * Specifies a `$center` or `$centerSphere` condition.
  4469. *
  4470. * ####Example
  4471. *
  4472. * var area = { center: [50, 50], radius: 10, unique: true }
  4473. * query.where('loc').within().circle(area)
  4474. * // alternatively
  4475. * query.circle('loc', area);
  4476. *
  4477. * // spherical calculations
  4478. * var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
  4479. * query.where('loc').within().circle(area)
  4480. * // alternatively
  4481. * query.circle('loc', area);
  4482. *
  4483. * @method circle
  4484. * @memberOf Query
  4485. * @instance
  4486. * @param {String} [path]
  4487. * @param {Object} area
  4488. * @return {Query} this
  4489. * @see $center http://docs.mongodb.org/manual/reference/operator/center/
  4490. * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
  4491. * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/
  4492. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4493. * @api public
  4494. */
  4495. /**
  4496. * _DEPRECATED_ Alias for [circle](#query_Query-circle)
  4497. *
  4498. * **Deprecated.** Use [circle](#query_Query-circle) instead.
  4499. *
  4500. * @deprecated
  4501. * @method center
  4502. * @memberOf Query
  4503. * @instance
  4504. * @api public
  4505. */
  4506. Query.prototype.center = Query.base.circle;
  4507. /**
  4508. * _DEPRECATED_ Specifies a `$centerSphere` condition
  4509. *
  4510. * **Deprecated.** Use [circle](#query_Query-circle) instead.
  4511. *
  4512. * ####Example
  4513. *
  4514. * var area = { center: [50, 50], radius: 10 };
  4515. * query.where('loc').within().centerSphere(area);
  4516. *
  4517. * @deprecated
  4518. * @param {String} [path]
  4519. * @param {Object} val
  4520. * @return {Query} this
  4521. * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing
  4522. * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/
  4523. * @api public
  4524. */
  4525. Query.prototype.centerSphere = function() {
  4526. if (arguments[0] && arguments[0].constructor.name === 'Object') {
  4527. arguments[0].spherical = true;
  4528. }
  4529. if (arguments[1] && arguments[1].constructor.name === 'Object') {
  4530. arguments[1].spherical = true;
  4531. }
  4532. Query.base.circle.apply(this, arguments);
  4533. };
  4534. /**
  4535. * Determines if field selection has been made.
  4536. *
  4537. * @method selected
  4538. * @memberOf Query
  4539. * @instance
  4540. * @return {Boolean}
  4541. * @api public
  4542. */
  4543. /**
  4544. * Determines if inclusive field selection has been made.
  4545. *
  4546. * query.selectedInclusively() // false
  4547. * query.select('name')
  4548. * query.selectedInclusively() // true
  4549. *
  4550. * @method selectedInclusively
  4551. * @memberOf Query
  4552. * @instance
  4553. * @return {Boolean}
  4554. * @api public
  4555. */
  4556. Query.prototype.selectedInclusively = function selectedInclusively() {
  4557. return isInclusive(this._fields);
  4558. };
  4559. /**
  4560. * Determines if exclusive field selection has been made.
  4561. *
  4562. * query.selectedExclusively() // false
  4563. * query.select('-name')
  4564. * query.selectedExclusively() // true
  4565. * query.selectedInclusively() // false
  4566. *
  4567. * @method selectedExclusively
  4568. * @memberOf Query
  4569. * @instance
  4570. * @return {Boolean}
  4571. * @api public
  4572. */
  4573. Query.prototype.selectedExclusively = function selectedExclusively() {
  4574. if (!this._fields) {
  4575. return false;
  4576. }
  4577. const keys = Object.keys(this._fields);
  4578. if (keys.length === 0) {
  4579. return false;
  4580. }
  4581. for (let i = 0; i < keys.length; ++i) {
  4582. const key = keys[i];
  4583. if (key === '_id') {
  4584. continue;
  4585. }
  4586. if (this._fields[key] === 0 || this._fields[key] === false) {
  4587. return true;
  4588. }
  4589. }
  4590. return false;
  4591. };
  4592. /*!
  4593. * Export
  4594. */
  4595. module.exports = Query;