query.js 167 KB

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