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 152KB

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