query.js 158 KB

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