Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query.js 138KB

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