query.js 165 KB

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