query.js 165 KB

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