query.js 171 KB

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