model.js 157 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const Aggregate = require('./aggregate');
  6. const ChangeStream = require('./cursor/ChangeStream');
  7. const Document = require('./document');
  8. const DocumentNotFoundError = require('./error').DocumentNotFoundError;
  9. const DivergentArrayError = require('./error').DivergentArrayError;
  10. const Error = require('./error');
  11. const EventEmitter = require('events').EventEmitter;
  12. const MongooseBuffer = require('./types/buffer');
  13. const OverwriteModelError = require('./error').OverwriteModelError;
  14. const PromiseProvider = require('./promise_provider');
  15. const Query = require('./query');
  16. const SaveOptions = require('./options/saveOptions');
  17. const Schema = require('./schema');
  18. const VersionError = require('./error').VersionError;
  19. const ParallelSaveError = require('./error').ParallelSaveError;
  20. const applyQueryMiddleware = require('./helpers/query/applyQueryMiddleware');
  21. const applyHooks = require('./helpers/model/applyHooks');
  22. const applyMethods = require('./helpers/model/applyMethods');
  23. const applyStaticHooks = require('./helpers/model/applyStaticHooks');
  24. const applyStatics = require('./helpers/model/applyStatics');
  25. const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
  26. const assignVals = require('./helpers/populate/assignVals');
  27. const castBulkWrite = require('./helpers/model/castBulkWrite');
  28. const discriminator = require('./helpers/model/discriminator');
  29. const getDiscriminatorByValue = require('./queryhelpers').getDiscriminatorByValue;
  30. const immediate = require('./helpers/immediate');
  31. const internalToObjectOptions = require('./options').internalToObjectOptions;
  32. const isPathExcluded = require('./helpers/projection/isPathExcluded');
  33. const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
  34. const get = require('./helpers/get');
  35. const getSchemaTypes = require('./helpers/populate/getSchemaTypes');
  36. const getVirtual = require('./helpers/populate/getVirtual');
  37. const leanPopulateMap = require('./helpers/populate/leanPopulateMap');
  38. const modifiedPaths = require('./helpers/update/modifiedPaths');
  39. const normalizeRefPath = require('./helpers/populate/normalizeRefPath');
  40. const parallel = require('async/parallel');
  41. const parallelLimit = require('async/parallelLimit');
  42. const util = require('util');
  43. const utils = require('./utils');
  44. const VERSION_WHERE = 1;
  45. const VERSION_INC = 2;
  46. const VERSION_ALL = VERSION_WHERE | VERSION_INC;
  47. const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
  48. const modelCollectionSymbol = Symbol.for('mongoose#Model#collection');
  49. const modelSymbol = require('./helpers/symbols').modelSymbol;
  50. const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
  51. const subclassedSymbol = Symbol('mongoose#Model#subclassed');
  52. /**
  53. * A Model is a class that's your primary tool for interacting with MongoDB.
  54. * An instance of a Model is called a [Document](./api.html#Document).
  55. *
  56. * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model`
  57. * class. You should not use the `mongoose.Model` class directly. The
  58. * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and
  59. * [`connection.model()`](./api.html#connection_Connection-model) functions
  60. * create subclasses of `mongoose.Model` as shown below.
  61. *
  62. * ####Example:
  63. *
  64. * // `UserModel` is a "Model", a subclass of `mongoose.Model`.
  65. * const UserModel = mongoose.model('User', new Schema({ name: String }));
  66. *
  67. * // You can use a Model to create new documents using `new`:
  68. * const userDoc = new UserModel({ name: 'Foo' });
  69. * await userDoc.save();
  70. *
  71. * // You also use a model to create queries:
  72. * const userFromDb = await UserModel.findOne({ name: 'Foo' });
  73. *
  74. * @param {Object} doc values for initial set
  75. * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projetion](./api.html#query_Query-select).
  76. * @inherits Document http://mongoosejs.com/docs/api.html#document-js
  77. * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.
  78. * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.
  79. * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event.
  80. * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed.
  81. * @api public
  82. */
  83. function Model(doc, fields, skipId) {
  84. if (fields instanceof Schema) {
  85. throw new TypeError('2nd argument to `Model` must be a POJO or string, ' +
  86. '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' +
  87. '`mongoose.Model()`.');
  88. }
  89. Document.call(this, doc, fields, skipId);
  90. }
  91. /*!
  92. * Inherits from Document.
  93. *
  94. * All Model.prototype features are available on
  95. * top level (non-sub) documents.
  96. */
  97. Model.prototype.__proto__ = Document.prototype;
  98. Model.prototype.$isMongooseModelPrototype = true;
  99. /**
  100. * Connection the model uses.
  101. *
  102. * @api public
  103. * @property db
  104. * @memberOf Model
  105. * @instance
  106. */
  107. Model.prototype.db;
  108. /**
  109. * Collection the model uses.
  110. *
  111. * This property is read-only. Modifying this property is a no-op.
  112. *
  113. * @api public
  114. * @property collection
  115. * @memberOf Model
  116. * @instance
  117. */
  118. Model.prototype.collection;
  119. /**
  120. * The name of the model
  121. *
  122. * @api public
  123. * @property modelName
  124. * @memberOf Model
  125. * @instance
  126. */
  127. Model.prototype.modelName;
  128. /**
  129. * Additional properties to attach to the query when calling `save()` and
  130. * `isNew` is false.
  131. *
  132. * @api public
  133. * @property $where
  134. * @memberOf Model
  135. * @instance
  136. */
  137. Model.prototype.$where;
  138. /**
  139. * If this is a discriminator model, `baseModelName` is the name of
  140. * the base model.
  141. *
  142. * @api public
  143. * @property baseModelName
  144. * @memberOf Model
  145. * @instance
  146. */
  147. Model.prototype.baseModelName;
  148. /**
  149. * Event emitter that reports any errors that occurred. Useful for global error
  150. * handling.
  151. *
  152. * ####Example:
  153. *
  154. * MyModel.events.on('error', err => console.log(err.message));
  155. *
  156. * // Prints a 'CastError' because of the above handler
  157. * await MyModel.findOne({ _id: 'notanid' }).catch(noop);
  158. *
  159. * @api public
  160. * @fires error whenever any query or model function errors
  161. * @memberOf Model
  162. * @static events
  163. */
  164. Model.events;
  165. /*!
  166. * Compiled middleware for this model. Set in `applyHooks()`.
  167. *
  168. * @api private
  169. * @property _middleware
  170. * @memberOf Model
  171. * @static
  172. */
  173. Model._middleware;
  174. /*!
  175. * ignore
  176. */
  177. function _applyCustomWhere(doc, where) {
  178. if (doc.$where == null) {
  179. return;
  180. }
  181. const keys = Object.keys(doc.$where);
  182. const len = keys.length;
  183. for (let i = 0; i < len; ++i) {
  184. where[keys[i]] = doc.$where[keys[i]];
  185. }
  186. }
  187. /*!
  188. * ignore
  189. */
  190. Model.prototype.$__handleSave = function(options, callback) {
  191. const _this = this;
  192. let saveOptions = {};
  193. if ('safe' in options) {
  194. _handleSafe(options);
  195. }
  196. applyWriteConcern(this.schema, options);
  197. if ('w' in options) {
  198. saveOptions.w = options.w;
  199. }
  200. if ('j' in options) {
  201. saveOptions.j = options.j;
  202. }
  203. if ('wtimeout' in options) {
  204. saveOptions.wtimeout = options.wtimeout;
  205. }
  206. if ('checkKeys' in options) {
  207. saveOptions.checkKeys = options.checkKeys;
  208. }
  209. const session = 'session' in options ? options.session : this.$session();
  210. if (session != null) {
  211. saveOptions.session = session;
  212. this.$session(session);
  213. }
  214. if (Object.keys(saveOptions).length === 0) {
  215. saveOptions = null;
  216. }
  217. if (this.isNew) {
  218. // send entire doc
  219. const obj = this.toObject(internalToObjectOptions);
  220. if ((obj || {})._id === void 0) {
  221. // documents must have an _id else mongoose won't know
  222. // what to update later if more changes are made. the user
  223. // wouldn't know what _id was generated by mongodb either
  224. // nor would the ObjectId generated by mongodb necessarily
  225. // match the schema definition.
  226. setTimeout(function() {
  227. callback(new Error('document must have an _id before saving'));
  228. }, 0);
  229. return;
  230. }
  231. this.$__version(true, obj);
  232. this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) {
  233. if (err) {
  234. _this.isNew = true;
  235. _this.emit('isNew', true);
  236. _this.constructor.emit('isNew', true);
  237. callback(err, null);
  238. return;
  239. }
  240. callback(null, ret);
  241. });
  242. this.$__reset();
  243. this.isNew = false;
  244. this.emit('isNew', false);
  245. this.constructor.emit('isNew', false);
  246. // Make it possible to retry the insert
  247. this.$__.inserting = true;
  248. } else {
  249. // Make sure we don't treat it as a new object on error,
  250. // since it already exists
  251. this.$__.inserting = false;
  252. const delta = this.$__delta();
  253. if (delta) {
  254. if (delta instanceof Error) {
  255. callback(delta);
  256. return;
  257. }
  258. const where = this.$__where(delta[0]);
  259. if (where instanceof Error) {
  260. callback(where);
  261. return;
  262. }
  263. _applyCustomWhere(this, where);
  264. this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, function(err, ret) {
  265. if (err) {
  266. callback(err);
  267. return;
  268. }
  269. ret.$where = where;
  270. callback(null, ret);
  271. });
  272. } else {
  273. this.$__reset();
  274. callback();
  275. return;
  276. }
  277. this.emit('isNew', false);
  278. this.constructor.emit('isNew', false);
  279. }
  280. };
  281. /*!
  282. * ignore
  283. */
  284. Model.prototype.$__save = function(options, callback) {
  285. this.$__handleSave(options, (error, result) => {
  286. if (error) {
  287. return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) {
  288. callback(error);
  289. });
  290. }
  291. // store the modified paths before the document is reset
  292. const modifiedPaths = this.modifiedPaths();
  293. this.$__reset();
  294. let numAffected = 0;
  295. if (get(options, 'safe.w') !== 0 && get(options, 'w') !== 0) {
  296. // Skip checking if write succeeded if writeConcern is set to
  297. // unacknowledged writes, because otherwise `numAffected` will always be 0
  298. if (result) {
  299. if (Array.isArray(result)) {
  300. numAffected = result.length;
  301. } else if (result.result && result.result.n !== undefined) {
  302. numAffected = result.result.n;
  303. } else if (result.result && result.result.nModified !== undefined) {
  304. numAffected = result.result.nModified;
  305. } else {
  306. numAffected = result;
  307. }
  308. }
  309. // was this an update that required a version bump?
  310. if (this.$__.version && !this.$__.inserting) {
  311. const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version);
  312. this.$__.version = undefined;
  313. const key = this.schema.options.versionKey;
  314. const version = this.getValue(key) || 0;
  315. if (numAffected <= 0) {
  316. // the update failed. pass an error back
  317. const err = this.$__.$versionError ||
  318. new VersionError(this, version, modifiedPaths);
  319. return callback(err);
  320. }
  321. // increment version if was successful
  322. if (doIncrement) {
  323. this.setValue(key, version + 1);
  324. }
  325. }
  326. if (result != null && numAffected <= 0) {
  327. error = new DocumentNotFoundError(result.$where);
  328. return this.schema.s.hooks.execPost('save:error', this, [this], { error: error }, function(error) {
  329. callback(error);
  330. });
  331. }
  332. }
  333. this.$__.saving = undefined;
  334. this.emit('save', this, numAffected);
  335. this.constructor.emit('save', this, numAffected);
  336. callback(null, this);
  337. });
  338. };
  339. /*!
  340. * ignore
  341. */
  342. function generateVersionError(doc, modifiedPaths) {
  343. const key = doc.schema.options.versionKey;
  344. if (!key) {
  345. return null;
  346. }
  347. const version = doc.getValue(key) || 0;
  348. return new VersionError(doc, version, modifiedPaths);
  349. }
  350. /**
  351. * Saves this document.
  352. *
  353. * ####Example:
  354. *
  355. * product.sold = Date.now();
  356. * product = await product.save();
  357. *
  358. * If save is successful, the returned promise will fulfill with the document
  359. * saved.
  360. *
  361. * ####Example:
  362. *
  363. * const newProduct = await product.save();
  364. * newProduct === product; // true
  365. *
  366. * @param {Object} [options] options optional options
  367. * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session).
  368. * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead.
  369. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
  370. * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern)
  371. * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern)
  372. * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern).
  373. * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names)
  374. * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`.
  375. * @param {Function} [fn] optional callback
  376. * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating).
  377. * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise.
  378. * @api public
  379. * @see middleware http://mongoosejs.com/docs/middleware.html
  380. */
  381. Model.prototype.save = function(options, fn) {
  382. let parallelSave;
  383. if (this.$__.saving) {
  384. parallelSave = new ParallelSaveError(this);
  385. } else {
  386. this.$__.saving = new ParallelSaveError(this);
  387. }
  388. if (typeof options === 'function') {
  389. fn = options;
  390. options = undefined;
  391. }
  392. if (fn) {
  393. fn = this.constructor.$wrapCallback(fn);
  394. }
  395. options = new SaveOptions(options);
  396. this.$__.$versionError = generateVersionError(this, this.modifiedPaths());
  397. return utils.promiseOrCallback(fn, cb => {
  398. if (parallelSave) {
  399. this.$__handleReject(parallelSave);
  400. return cb(parallelSave);
  401. }
  402. this.$__.saveOptions = options;
  403. this.$__save(options, error => {
  404. this.$__.saving = undefined;
  405. delete this.$__.saveOptions;
  406. if (error) {
  407. this.$__handleReject(error);
  408. return cb(error);
  409. }
  410. cb(null, this);
  411. });
  412. }, this.constructor.events);
  413. };
  414. /*!
  415. * Determines whether versioning should be skipped for the given path
  416. *
  417. * @param {Document} self
  418. * @param {String} path
  419. * @return {Boolean} true if versioning should be skipped for the given path
  420. */
  421. function shouldSkipVersioning(self, path) {
  422. const skipVersioning = self.schema.options.skipVersioning;
  423. if (!skipVersioning) return false;
  424. // Remove any array indexes from the path
  425. path = path.replace(/\.\d+\./, '.');
  426. return skipVersioning[path];
  427. }
  428. /*!
  429. * Apply the operation to the delta (update) clause as
  430. * well as track versioning for our where clause.
  431. *
  432. * @param {Document} self
  433. * @param {Object} where
  434. * @param {Object} delta
  435. * @param {Object} data
  436. * @param {Mixed} val
  437. * @param {String} [operation]
  438. */
  439. function operand(self, where, delta, data, val, op) {
  440. // delta
  441. op || (op = '$set');
  442. if (!delta[op]) delta[op] = {};
  443. delta[op][data.path] = val;
  444. // disabled versioning?
  445. if (self.schema.options.versionKey === false) return;
  446. // path excluded from versioning?
  447. if (shouldSkipVersioning(self, data.path)) return;
  448. // already marked for versioning?
  449. if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return;
  450. switch (op) {
  451. case '$set':
  452. case '$unset':
  453. case '$pop':
  454. case '$pull':
  455. case '$pullAll':
  456. case '$push':
  457. case '$addToSet':
  458. break;
  459. default:
  460. // nothing to do
  461. return;
  462. }
  463. // ensure updates sent with positional notation are
  464. // editing the correct array element.
  465. // only increment the version if an array position changes.
  466. // modifying elements of an array is ok if position does not change.
  467. if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') {
  468. self.$__.version = VERSION_INC;
  469. } else if (/^\$p/.test(op)) {
  470. // potentially changing array positions
  471. self.increment();
  472. } else if (Array.isArray(val)) {
  473. // $set an array
  474. self.increment();
  475. } else if (/\.\d+\.|\.\d+$/.test(data.path)) {
  476. // now handling $set, $unset
  477. // subpath of array
  478. self.$__.version = VERSION_WHERE;
  479. }
  480. }
  481. /*!
  482. * Compiles an update and where clause for a `val` with _atomics.
  483. *
  484. * @param {Document} self
  485. * @param {Object} where
  486. * @param {Object} delta
  487. * @param {Object} data
  488. * @param {Array} value
  489. */
  490. function handleAtomics(self, where, delta, data, value) {
  491. if (delta.$set && delta.$set[data.path]) {
  492. // $set has precedence over other atomics
  493. return;
  494. }
  495. if (typeof value.$__getAtomics === 'function') {
  496. value.$__getAtomics().forEach(function(atomic) {
  497. const op = atomic[0];
  498. const val = atomic[1];
  499. operand(self, where, delta, data, val, op);
  500. });
  501. return;
  502. }
  503. // legacy support for plugins
  504. const atomics = value[arrayAtomicsSymbol];
  505. const ops = Object.keys(atomics);
  506. let i = ops.length;
  507. let val;
  508. let op;
  509. if (i === 0) {
  510. // $set
  511. if (utils.isMongooseObject(value)) {
  512. value = value.toObject({depopulate: 1, _isNested: true});
  513. } else if (value.valueOf) {
  514. value = value.valueOf();
  515. }
  516. return operand(self, where, delta, data, value);
  517. }
  518. function iter(mem) {
  519. return utils.isMongooseObject(mem)
  520. ? mem.toObject({depopulate: 1, _isNested: true})
  521. : mem;
  522. }
  523. while (i--) {
  524. op = ops[i];
  525. val = atomics[op];
  526. if (utils.isMongooseObject(val)) {
  527. val = val.toObject({depopulate: true, transform: false, _isNested: true});
  528. } else if (Array.isArray(val)) {
  529. val = val.map(iter);
  530. } else if (val.valueOf) {
  531. val = val.valueOf();
  532. }
  533. if (op === '$addToSet') {
  534. val = {$each: val};
  535. }
  536. operand(self, where, delta, data, val, op);
  537. }
  538. }
  539. /**
  540. * Produces a special query document of the modified properties used in updates.
  541. *
  542. * @api private
  543. * @method $__delta
  544. * @memberOf Model
  545. * @instance
  546. */
  547. Model.prototype.$__delta = function() {
  548. const dirty = this.$__dirty();
  549. if (!dirty.length && VERSION_ALL !== this.$__.version) {
  550. return;
  551. }
  552. const where = {};
  553. const delta = {};
  554. const len = dirty.length;
  555. const divergent = [];
  556. let d = 0;
  557. where._id = this._doc._id;
  558. // If `_id` is an object, need to depopulate, but also need to be careful
  559. // because `_id` can technically be null (see gh-6406)
  560. if (get(where, '_id.$__', null) != null) {
  561. where._id = where._id.toObject({ transform: false, depopulate: true });
  562. }
  563. for (; d < len; ++d) {
  564. const data = dirty[d];
  565. let value = data.value;
  566. const match = checkDivergentArray(this, data.path, value);
  567. if (match) {
  568. divergent.push(match);
  569. continue;
  570. }
  571. const pop = this.populated(data.path, true);
  572. if (!pop && this.$__.selected) {
  573. // If any array was selected using an $elemMatch projection, we alter the path and where clause
  574. // NOTE: MongoDB only supports projected $elemMatch on top level array.
  575. const pathSplit = data.path.split('.');
  576. const top = pathSplit[0];
  577. if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) {
  578. // If the selected array entry was modified
  579. if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') {
  580. where[top] = this.$__.selected[top];
  581. pathSplit[1] = '$';
  582. data.path = pathSplit.join('.');
  583. }
  584. // if the selected array was modified in any other way throw an error
  585. else {
  586. divergent.push(data.path);
  587. continue;
  588. }
  589. }
  590. }
  591. if (divergent.length) continue;
  592. if (value === undefined) {
  593. operand(this, where, delta, data, 1, '$unset');
  594. } else if (value === null) {
  595. operand(this, where, delta, data, null);
  596. } else if (value.isMongooseArray && value.$path() && value[arrayAtomicsSymbol]) {
  597. // arrays and other custom types (support plugins etc)
  598. handleAtomics(this, where, delta, data, value);
  599. } else if (value[MongooseBuffer.pathSymbol] && Buffer.isBuffer(value)) {
  600. // MongooseBuffer
  601. value = value.toObject();
  602. operand(this, where, delta, data, value);
  603. } else {
  604. value = utils.clone(value, {
  605. depopulate: true,
  606. transform: false,
  607. virtuals: false,
  608. getters: false,
  609. _isNested: true
  610. });
  611. operand(this, where, delta, data, value);
  612. }
  613. }
  614. if (divergent.length) {
  615. return new DivergentArrayError(divergent);
  616. }
  617. if (this.$__.version) {
  618. this.$__version(where, delta);
  619. }
  620. return [where, delta];
  621. };
  622. /*!
  623. * Determine if array was populated with some form of filter and is now
  624. * being updated in a manner which could overwrite data unintentionally.
  625. *
  626. * @see https://github.com/Automattic/mongoose/issues/1334
  627. * @param {Document} doc
  628. * @param {String} path
  629. * @return {String|undefined}
  630. */
  631. function checkDivergentArray(doc, path, array) {
  632. // see if we populated this path
  633. const pop = doc.populated(path, true);
  634. if (!pop && doc.$__.selected) {
  635. // If any array was selected using an $elemMatch projection, we deny the update.
  636. // NOTE: MongoDB only supports projected $elemMatch on top level array.
  637. const top = path.split('.')[0];
  638. if (doc.$__.selected[top + '.$']) {
  639. return top;
  640. }
  641. }
  642. if (!(pop && array && array.isMongooseArray)) return;
  643. // If the array was populated using options that prevented all
  644. // documents from being returned (match, skip, limit) or they
  645. // deselected the _id field, $pop and $set of the array are
  646. // not safe operations. If _id was deselected, we do not know
  647. // how to remove elements. $pop will pop off the _id from the end
  648. // of the array in the db which is not guaranteed to be the
  649. // same as the last element we have here. $set of the entire array
  650. // would be similarily destructive as we never received all
  651. // elements of the array and potentially would overwrite data.
  652. const check = pop.options.match ||
  653. pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted
  654. pop.options.options && pop.options.options.skip || // 0 is permitted
  655. pop.options.select && // deselected _id?
  656. (pop.options.select._id === 0 ||
  657. /\s?-_id\s?/.test(pop.options.select));
  658. if (check) {
  659. const atomics = array[arrayAtomicsSymbol];
  660. if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) {
  661. return path;
  662. }
  663. }
  664. }
  665. /**
  666. * Appends versioning to the where and update clauses.
  667. *
  668. * @api private
  669. * @method $__version
  670. * @memberOf Model
  671. * @instance
  672. */
  673. Model.prototype.$__version = function(where, delta) {
  674. const key = this.schema.options.versionKey;
  675. if (where === true) {
  676. // this is an insert
  677. if (key) this.setValue(key, delta[key] = 0);
  678. return;
  679. }
  680. // updates
  681. // only apply versioning if our versionKey was selected. else
  682. // there is no way to select the correct version. we could fail
  683. // fast here and force them to include the versionKey but
  684. // thats a bit intrusive. can we do this automatically?
  685. if (!this.isSelected(key)) {
  686. return;
  687. }
  688. // $push $addToSet don't need the where clause set
  689. if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {
  690. const value = this.getValue(key);
  691. if (value != null) where[key] = value;
  692. }
  693. if (VERSION_INC === (VERSION_INC & this.$__.version)) {
  694. if (get(delta.$set, key, null) != null) {
  695. // Version key is getting set, means we'll increment the doc's version
  696. // after a successful save, so we should set the incremented version so
  697. // future saves don't fail (gh-5779)
  698. ++delta.$set[key];
  699. } else {
  700. delta.$inc = delta.$inc || {};
  701. delta.$inc[key] = 1;
  702. }
  703. }
  704. };
  705. /**
  706. * Signal that we desire an increment of this documents version.
  707. *
  708. * ####Example:
  709. *
  710. * Model.findById(id, function (err, doc) {
  711. * doc.increment();
  712. * doc.save(function (err) { .. })
  713. * })
  714. *
  715. * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey
  716. * @api public
  717. */
  718. Model.prototype.increment = function increment() {
  719. this.$__.version = VERSION_ALL;
  720. return this;
  721. };
  722. /**
  723. * Returns a query object
  724. *
  725. * @api private
  726. * @method $__where
  727. * @memberOf Model
  728. * @instance
  729. */
  730. Model.prototype.$__where = function _where(where) {
  731. where || (where = {});
  732. if (!where._id) {
  733. where._id = this._doc._id;
  734. }
  735. if (this._doc._id === void 0) {
  736. return new Error('No _id found on document!');
  737. }
  738. return where;
  739. };
  740. /**
  741. * Removes this document from the db.
  742. *
  743. * ####Example:
  744. * product.remove(function (err, product) {
  745. * if (err) return handleError(err);
  746. * Product.findById(product._id, function (err, product) {
  747. * console.log(product) // null
  748. * })
  749. * })
  750. *
  751. *
  752. * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors
  753. *
  754. * ####Example:
  755. * product.remove().then(function (product) {
  756. * ...
  757. * }).catch(function (err) {
  758. * assert.ok(err)
  759. * })
  760. *
  761. * @param {function(err,product)} [fn] optional callback
  762. * @return {Promise} Promise
  763. * @api public
  764. */
  765. Model.prototype.remove = function remove(options, fn) {
  766. if (typeof options === 'function') {
  767. fn = options;
  768. options = undefined;
  769. }
  770. if (!options) {
  771. options = {};
  772. }
  773. if (fn) {
  774. fn = this.constructor.$wrapCallback(fn);
  775. }
  776. return utils.promiseOrCallback(fn, cb => {
  777. this.$__remove(options, cb);
  778. }, this.constructor.events);
  779. };
  780. /**
  781. * Alias for remove
  782. */
  783. Model.prototype.delete = Model.prototype.remove;
  784. /**
  785. * Removes this document from the db. Equivalent to `.remove()`.
  786. *
  787. * ####Example:
  788. * product = await product.deleteOne();
  789. * await Product.findById(product._id); // null
  790. *
  791. * @param {function(err,product)} [fn] optional callback
  792. * @return {Promise} Promise
  793. * @api public
  794. */
  795. Model.prototype.deleteOne = function deleteOne(options, fn) {
  796. if (typeof options === 'function') {
  797. fn = options;
  798. options = undefined;
  799. }
  800. if (!options) {
  801. options = {};
  802. }
  803. if (fn) {
  804. fn = this.constructor.$wrapCallback(fn);
  805. }
  806. return utils.promiseOrCallback(fn, cb => {
  807. this.$__deleteOne(options, cb);
  808. }, this.constructor.events);
  809. };
  810. /*!
  811. * ignore
  812. */
  813. Model.prototype.$__remove = function $__remove(options, cb) {
  814. if (this.$__.isDeleted) {
  815. return immediate(() => cb(null, this));
  816. }
  817. const where = this.$__where();
  818. if (where instanceof Error) {
  819. return cb(where);
  820. }
  821. _applyCustomWhere(this, where);
  822. if (this.$session() != null) {
  823. options = options || {};
  824. if (!('session' in options)) {
  825. options.session = this.$session();
  826. }
  827. }
  828. this[modelCollectionSymbol].deleteOne(where, options, err => {
  829. if (!err) {
  830. this.$__.isDeleted = true;
  831. this.emit('remove', this);
  832. this.constructor.emit('remove', this);
  833. return cb(null, this);
  834. }
  835. this.$__.isDeleted = false;
  836. cb(err);
  837. });
  838. };
  839. /*!
  840. * ignore
  841. */
  842. Model.prototype.$__deleteOne = Model.prototype.$__remove;
  843. /**
  844. * Returns another Model instance.
  845. *
  846. * ####Example:
  847. *
  848. * var doc = new Tank;
  849. * doc.model('User').findById(id, callback);
  850. *
  851. * @param {String} name model name
  852. * @api public
  853. */
  854. Model.prototype.model = function model(name) {
  855. return this.db.model(name);
  856. };
  857. /**
  858. * Adds a discriminator type.
  859. *
  860. * ####Example:
  861. *
  862. * function BaseSchema() {
  863. * Schema.apply(this, arguments);
  864. *
  865. * this.add({
  866. * name: String,
  867. * createdAt: Date
  868. * });
  869. * }
  870. * util.inherits(BaseSchema, Schema);
  871. *
  872. * var PersonSchema = new BaseSchema();
  873. * var BossSchema = new BaseSchema({ department: String });
  874. *
  875. * var Person = mongoose.model('Person', PersonSchema);
  876. * var Boss = Person.discriminator('Boss', BossSchema);
  877. * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`
  878. *
  879. * var employeeSchema = new Schema({ boss: ObjectId });
  880. * var Employee = Person.discriminator('Employee', employeeSchema, 'staff');
  881. * new Employee().__t; // "staff" because of 3rd argument above
  882. *
  883. * @param {String} name discriminator model name
  884. * @param {Schema} schema discriminator model schema
  885. * @param {String} value the string stored in the `discriminatorKey` property
  886. * @api public
  887. */
  888. Model.discriminator = function(name, schema, value) {
  889. let model;
  890. if (typeof name === 'function') {
  891. model = name;
  892. name = utils.getFunctionName(model);
  893. if (!(model.prototype instanceof Model)) {
  894. throw new Error('The provided class ' + name + ' must extend Model');
  895. }
  896. }
  897. schema = discriminator(this, name, schema, value, true);
  898. if (this.db.models[name]) {
  899. throw new OverwriteModelError(name);
  900. }
  901. schema.$isRootDiscriminator = true;
  902. schema.$globalPluginsApplied = true;
  903. model = this.db.model(model || name, schema, this.collection.name);
  904. this.discriminators[name] = model;
  905. const d = this.discriminators[name];
  906. d.prototype.__proto__ = this.prototype;
  907. Object.defineProperty(d, 'baseModelName', {
  908. value: this.modelName,
  909. configurable: true,
  910. writable: false
  911. });
  912. // apply methods and statics
  913. applyMethods(d, schema);
  914. applyStatics(d, schema);
  915. if (this[subclassedSymbol] != null) {
  916. for (const submodel of this[subclassedSymbol]) {
  917. submodel.discriminators = submodel.discriminators || {};
  918. submodel.discriminators[name] =
  919. model.__subclass(model.db, schema, submodel.collection.name);
  920. }
  921. }
  922. return d;
  923. };
  924. // Model (class) features
  925. /*!
  926. * Give the constructor the ability to emit events.
  927. */
  928. for (const i in EventEmitter.prototype) {
  929. Model[i] = EventEmitter.prototype[i];
  930. }
  931. /**
  932. * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/),
  933. * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
  934. *
  935. * Mongoose calls this function automatically when a model is created using
  936. * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or
  937. * * [`connection.model()`](/docs/api.html#connection_Connection-model), so you
  938. * don't need to call it. This function is also idempotent, so you may call it
  939. * to get back a promise that will resolve when your indexes are finished
  940. * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes)
  941. *
  942. * ####Example:
  943. *
  944. * var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  945. * // This calls `Event.init()` implicitly, so you don't need to call
  946. * // `Event.init()` on your own.
  947. * var Event = mongoose.model('Event', eventSchema);
  948. *
  949. * Event.init().then(function(Event) {
  950. * // You can also use `Event.on('index')` if you prefer event emitters
  951. * // over promises.
  952. * console.log('Indexes are done building!');
  953. * });
  954. *
  955. * @api public
  956. * @param {Function} [callback]
  957. * @returns {Promise}
  958. */
  959. Model.init = function init(callback) {
  960. this.schema.emit('init', this);
  961. if (this.$init != null) {
  962. if (callback) {
  963. this.$init.then(() => callback(), err => callback(err));
  964. return null;
  965. }
  966. return this.$init;
  967. }
  968. const Promise = PromiseProvider.get();
  969. const autoIndex = this.schema.options.autoIndex == null ?
  970. this.db.config.autoIndex :
  971. this.schema.options.autoIndex;
  972. const autoCreate = this.schema.options.autoCreate == null ?
  973. this.db.config.autoCreate :
  974. this.schema.options.autoCreate;
  975. const _ensureIndexes = autoIndex ?
  976. cb => this.ensureIndexes({ _automatic: true }, cb) :
  977. cb => cb();
  978. const _createCollection = autoCreate ?
  979. cb => this.createCollection({}, cb) :
  980. cb => cb();
  981. this.$init = new Promise((resolve, reject) => {
  982. _createCollection(error => {
  983. if (error) {
  984. return reject(error);
  985. }
  986. _ensureIndexes(error => {
  987. if (error) {
  988. return reject(error);
  989. }
  990. resolve(this);
  991. });
  992. });
  993. });
  994. if (callback) {
  995. this.$init.then(() => callback(), err => callback(err));
  996. this.$caught = true;
  997. return null;
  998. } else {
  999. const _catch = this.$init.catch;
  1000. const _this = this;
  1001. this.$init.catch = function() {
  1002. this.$caught = true;
  1003. return _catch.apply(_this.$init, arguments);
  1004. };
  1005. }
  1006. return this.$init;
  1007. };
  1008. /**
  1009. * Create the collection for this model. By default, if no indexes are specified,
  1010. * mongoose will not create the collection for the model until any documents are
  1011. * created. Use this method to create the collection explicitly.
  1012. *
  1013. * Note 1: You may need to call this before starting a transaction
  1014. * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations
  1015. *
  1016. * Note 2: You don't have to call this if your schema contains index or unique field.
  1017. * In that case, just use `Model.init()`
  1018. *
  1019. * ####Example:
  1020. *
  1021. * var userSchema = new Schema({ name: String })
  1022. * var User = mongoose.model('User', userSchema);
  1023. *
  1024. * User.createCollection().then(function(collection) {
  1025. * console.log('Collection is created!');
  1026. * });
  1027. *
  1028. * @api public
  1029. * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection)
  1030. * @param {Function} [callback]
  1031. * @returns {Promise}
  1032. */
  1033. Model.createCollection = function createCollection(options, callback) {
  1034. if (typeof options === 'string') {
  1035. throw new Error('You can\'t specify a new collection name in Model.createCollection.' +
  1036. 'This is not like Connection.createCollection. Only options are accepted here.');
  1037. } else if (typeof options === 'function') {
  1038. callback = options;
  1039. options = null;
  1040. }
  1041. if (callback) {
  1042. callback = this.$wrapCallback(callback);
  1043. }
  1044. const schemaCollation = get(this, 'schema.options.collation', null);
  1045. if (schemaCollation != null) {
  1046. options = Object.assign({ collation: schemaCollation }, options);
  1047. }
  1048. return utils.promiseOrCallback(callback, cb => {
  1049. this.db.createCollection(this.collection.collectionName, options, utils.tick((error) => {
  1050. if (error) {
  1051. return cb(error);
  1052. }
  1053. this.collection = this.db.collection(this.collection.collectionName, options);
  1054. cb(null, this.collection);
  1055. }));
  1056. }, this.events);
  1057. };
  1058. /**
  1059. * Makes the indexes in MongoDB match the indexes defined in this model's
  1060. * schema. This function will drop any indexes that are not defined in
  1061. * the model's schema except the `_id` index, and build any indexes that
  1062. * are in your schema but not in MongoDB.
  1063. *
  1064. * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes)
  1065. * for more information.
  1066. *
  1067. * ####Example:
  1068. *
  1069. * const schema = new Schema({ name: { type: String, unique: true } });
  1070. * const Customer = mongoose.model('Customer', schema);
  1071. * await Customer.createIndex({ age: 1 }); // Index is not in schema
  1072. * // Will drop the 'age' index and create an index on `name`
  1073. * await Customer.syncIndexes();
  1074. *
  1075. * @param {Object} [options] options to pass to `ensureIndexes()`
  1076. * @param {Function} [callback] optional callback
  1077. * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback.
  1078. * @api public
  1079. */
  1080. Model.syncIndexes = function syncIndexes(options, callback) {
  1081. callback = this.$wrapCallback(callback);
  1082. const dropNonSchemaIndexes = (cb) => {
  1083. this.listIndexes((err, indexes) => {
  1084. if (err != null) {
  1085. return cb(err);
  1086. }
  1087. const schemaIndexes = this.schema.indexes();
  1088. const toDrop = [];
  1089. for (const index of indexes) {
  1090. let found = false;
  1091. // Never try to drop `_id` index, MongoDB server doesn't allow it
  1092. if (index.key._id) {
  1093. continue;
  1094. }
  1095. for (const schemaIndex of schemaIndexes) {
  1096. const key = schemaIndex[0];
  1097. const options = _decorateDiscriminatorIndexOptions(this,
  1098. utils.clone(schemaIndex[1]));
  1099. // If these options are different, need to rebuild the index
  1100. const optionKeys = ['unique', 'partialFilterExpression', 'sparse', 'expireAfterSeconds'];
  1101. const indexCopy = Object.assign({}, index);
  1102. for (const key of optionKeys) {
  1103. if (!(key in options) && !(key in indexCopy)) {
  1104. continue;
  1105. }
  1106. indexCopy[key] = options[key];
  1107. }
  1108. if (utils.deepEqual(key, index.key) &&
  1109. utils.deepEqual(index, indexCopy)) {
  1110. found = true;
  1111. break;
  1112. }
  1113. }
  1114. if (!found) {
  1115. toDrop.push(index.name);
  1116. }
  1117. }
  1118. if (toDrop.length === 0) {
  1119. return cb(null, []);
  1120. }
  1121. dropIndexes(toDrop, cb);
  1122. });
  1123. };
  1124. const dropIndexes = (toDrop, cb) => {
  1125. let remaining = toDrop.length;
  1126. let error = false;
  1127. toDrop.forEach(indexName => {
  1128. this.collection.dropIndex(indexName, err => {
  1129. if (err != null) {
  1130. error = true;
  1131. return cb(err);
  1132. }
  1133. if (!error) {
  1134. --remaining || cb(null, toDrop);
  1135. }
  1136. });
  1137. });
  1138. };
  1139. return utils.promiseOrCallback(callback, cb => {
  1140. dropNonSchemaIndexes((err, dropped) => {
  1141. if (err != null) {
  1142. return cb(err);
  1143. }
  1144. this.createIndexes(options, err => {
  1145. if (err != null) {
  1146. return cb(err);
  1147. }
  1148. cb(null, dropped);
  1149. });
  1150. });
  1151. }, this.events);
  1152. };
  1153. /**
  1154. * Lists the indexes currently defined in MongoDB. This may or may not be
  1155. * the same as the indexes defined in your schema depending on whether you
  1156. * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you
  1157. * build indexes manually.
  1158. *
  1159. * @param {Function} [cb] optional callback
  1160. * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback.
  1161. * @api public
  1162. */
  1163. Model.listIndexes = function init(callback) {
  1164. callback = this.$wrapCallback(callback);
  1165. const _listIndexes = cb => {
  1166. this.collection.listIndexes().toArray(cb);
  1167. };
  1168. return utils.promiseOrCallback(callback, cb => {
  1169. // Buffering
  1170. if (this.collection.buffer) {
  1171. this.collection.addQueue(_listIndexes, [cb]);
  1172. } else {
  1173. _listIndexes(cb);
  1174. }
  1175. }, this.events);
  1176. };
  1177. /**
  1178. * Sends `createIndex` commands to mongo for each index declared in the schema.
  1179. * The `createIndex` commands are sent in series.
  1180. *
  1181. * ####Example:
  1182. *
  1183. * Event.ensureIndexes(function (err) {
  1184. * if (err) return handleError(err);
  1185. * });
  1186. *
  1187. * After completion, an `index` event is emitted on this `Model` passing an error if one occurred.
  1188. *
  1189. * ####Example:
  1190. *
  1191. * var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  1192. * var Event = mongoose.model('Event', eventSchema);
  1193. *
  1194. * Event.on('index', function (err) {
  1195. * if (err) console.error(err); // error occurred during index creation
  1196. * })
  1197. *
  1198. * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._
  1199. *
  1200. * @param {Object} [options] internal options
  1201. * @param {Function} [cb] optional callback
  1202. * @return {Promise}
  1203. * @api public
  1204. */
  1205. Model.ensureIndexes = function ensureIndexes(options, callback) {
  1206. if (typeof options === 'function') {
  1207. callback = options;
  1208. options = null;
  1209. }
  1210. if (callback) {
  1211. callback = this.$wrapCallback(callback);
  1212. }
  1213. return utils.promiseOrCallback(callback, cb => {
  1214. _ensureIndexes(this, options || {}, error => {
  1215. if (error) {
  1216. return cb(error);
  1217. }
  1218. cb(null);
  1219. });
  1220. }, this.events);
  1221. };
  1222. /**
  1223. * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
  1224. * function.
  1225. *
  1226. * @param {Object} [options] internal options
  1227. * @param {Function} [cb] optional callback
  1228. * @return {Promise}
  1229. * @api public
  1230. */
  1231. Model.createIndexes = function createIndexes(options, callback) {
  1232. if (typeof options === 'function') {
  1233. callback = options;
  1234. options = {};
  1235. }
  1236. options = options || {};
  1237. options.createIndex = true;
  1238. return this.ensureIndexes(options, callback);
  1239. };
  1240. /*!
  1241. * ignore
  1242. */
  1243. function _ensureIndexes(model, options, callback) {
  1244. const indexes = model.schema.indexes();
  1245. options = options || {};
  1246. const done = function(err) {
  1247. if (err && !model.$caught) {
  1248. model.emit('error', err);
  1249. }
  1250. model.emit('index', err);
  1251. callback && callback(err);
  1252. };
  1253. for (const index of indexes) {
  1254. const keys = Object.keys(index[0]);
  1255. if (keys.length === 1 && keys[0] === '_id' && index[0]._id !== 'hashed') {
  1256. console.warn('mongoose: Cannot specify a custom index on `_id` for ' +
  1257. 'model name "' + model.modelName + '", ' +
  1258. 'MongoDB does not allow overwriting the default `_id` index. See ' +
  1259. 'http://bit.ly/mongodb-id-index');
  1260. }
  1261. }
  1262. if (!indexes.length) {
  1263. immediate(function() {
  1264. done();
  1265. });
  1266. return;
  1267. }
  1268. // Indexes are created one-by-one to support how MongoDB < 2.4 deals
  1269. // with background indexes.
  1270. const indexSingleDone = function(err, fields, options, name) {
  1271. model.emit('index-single-done', err, fields, options, name);
  1272. };
  1273. const indexSingleStart = function(fields, options) {
  1274. model.emit('index-single-start', fields, options);
  1275. };
  1276. const create = function() {
  1277. if (options._automatic) {
  1278. if (model.schema.options.autoIndex === false ||
  1279. (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) {
  1280. return done();
  1281. }
  1282. }
  1283. const index = indexes.shift();
  1284. if (!index) {
  1285. return done();
  1286. }
  1287. const indexFields = utils.clone(index[0]);
  1288. const indexOptions = utils.clone(index[1]);
  1289. _decorateDiscriminatorIndexOptions(model, indexOptions);
  1290. if ('safe' in options) {
  1291. _handleSafe(options);
  1292. }
  1293. applyWriteConcern(model.schema, indexOptions);
  1294. indexSingleStart(indexFields, options);
  1295. let useCreateIndex = !!model.base.options.useCreateIndex;
  1296. if ('useCreateIndex' in model.db.config) {
  1297. useCreateIndex = !!model.db.config.useCreateIndex;
  1298. }
  1299. if ('createIndex' in options) {
  1300. useCreateIndex = !!options.createIndex;
  1301. }
  1302. const methodName = useCreateIndex ? 'createIndex' : 'ensureIndex';
  1303. model.collection[methodName](indexFields, indexOptions, utils.tick(function(err, name) {
  1304. indexSingleDone(err, indexFields, indexOptions, name);
  1305. if (err) {
  1306. return done(err);
  1307. }
  1308. create();
  1309. }));
  1310. };
  1311. immediate(function() {
  1312. // If buffering is off, do this manually.
  1313. if (options._automatic && !model.collection.collection) {
  1314. model.collection.addQueue(create, []);
  1315. } else {
  1316. create();
  1317. }
  1318. });
  1319. }
  1320. function _decorateDiscriminatorIndexOptions(model, indexOptions) {
  1321. // If the model is a discriminator and it has a unique index, add a
  1322. // partialFilterExpression by default so the unique index will only apply
  1323. // to that discriminator.
  1324. if (model.baseModelName != null && indexOptions.unique &&
  1325. !('partialFilterExpression' in indexOptions) &&
  1326. !('sparse' in indexOptions)) {
  1327. const value = (
  1328. model.schema.discriminatorMapping &&
  1329. model.schema.discriminatorMapping.value
  1330. ) || model.modelName;
  1331. indexOptions.partialFilterExpression = {
  1332. [model.schema.options.discriminatorKey]: value
  1333. };
  1334. }
  1335. return indexOptions;
  1336. }
  1337. const safeDeprecationWarning = 'Mongoose: the `safe` option for `save()` is ' +
  1338. 'deprecated. Use the `w` option instead: http://bit.ly/mongoose-save';
  1339. const _handleSafe = util.deprecate(function _handleSafe(options) {
  1340. if (options.safe) {
  1341. if (typeof options.safe === 'boolean') {
  1342. options.w = options.safe;
  1343. delete options.safe;
  1344. }
  1345. if (typeof options.safe === 'object') {
  1346. options.w = options.safe.w;
  1347. options.j = options.safe.j;
  1348. options.wtimeout = options.safe.wtimeout;
  1349. delete options.safe;
  1350. }
  1351. }
  1352. }, safeDeprecationWarning);
  1353. /**
  1354. * Schema the model uses.
  1355. *
  1356. * @property schema
  1357. * @receiver Model
  1358. * @api public
  1359. * @memberOf Model
  1360. */
  1361. Model.schema;
  1362. /*!
  1363. * Connection instance the model uses.
  1364. *
  1365. * @property db
  1366. * @api public
  1367. * @memberOf Model
  1368. */
  1369. Model.db;
  1370. /*!
  1371. * Collection the model uses.
  1372. *
  1373. * @property collection
  1374. * @api public
  1375. * @memberOf Model
  1376. */
  1377. Model.collection;
  1378. /**
  1379. * Base Mongoose instance the model uses.
  1380. *
  1381. * @property base
  1382. * @api public
  1383. * @memberOf Model
  1384. */
  1385. Model.base;
  1386. /**
  1387. * Registered discriminators for this model.
  1388. *
  1389. * @property discriminators
  1390. * @api public
  1391. * @memberOf Model
  1392. */
  1393. Model.discriminators;
  1394. /**
  1395. * Translate any aliases fields/conditions so the final query or document object is pure
  1396. *
  1397. * ####Example:
  1398. *
  1399. * Character
  1400. * .find(Character.translateAliases({
  1401. * '名': 'Eddard Stark' // Alias for 'name'
  1402. * })
  1403. * .exec(function(err, characters) {})
  1404. *
  1405. * ####Note:
  1406. * Only translate arguments of object type anything else is returned raw
  1407. *
  1408. * @param {Object} raw fields/conditions that may contain aliased keys
  1409. * @return {Object} the translated 'pure' fields/conditions
  1410. */
  1411. Model.translateAliases = function translateAliases(fields) {
  1412. const translate = (key, value) => {
  1413. let alias;
  1414. const translated = [];
  1415. const fieldKeys = key.split('.');
  1416. let currentSchema = this.schema;
  1417. for (const i in fieldKeys) {
  1418. const name = fieldKeys[i];
  1419. if (currentSchema && currentSchema.aliases[name]) {
  1420. alias = currentSchema.aliases[name];
  1421. // Alias found,
  1422. translated.push(alias);
  1423. } else {
  1424. // Alias not found, so treat as un-aliased key
  1425. translated.push(name);
  1426. }
  1427. // Check if aliased path is a schema
  1428. if (currentSchema && currentSchema.paths[alias]) {
  1429. currentSchema = currentSchema.paths[alias].schema;
  1430. }
  1431. else
  1432. currentSchema = null;
  1433. }
  1434. const translatedKey = translated.join('.');
  1435. if (fields instanceof Map)
  1436. fields.set(translatedKey, value);
  1437. else
  1438. fields[translatedKey] = value;
  1439. if (translatedKey !== key) {
  1440. // We'll be using the translated key instead
  1441. if (fields instanceof Map) {
  1442. // Delete from map
  1443. fields.delete(key);
  1444. } else {
  1445. // Delete from object
  1446. delete fields[key]; // We'll be using the translated key instead
  1447. }
  1448. }
  1449. return fields;
  1450. };
  1451. if (typeof fields === 'object') {
  1452. // Fields is an object (query conditions or document fields)
  1453. if (fields instanceof Map) {
  1454. // A Map was supplied
  1455. for (const field of new Map(fields)) {
  1456. fields = translate(field[0], field[1]);
  1457. }
  1458. } else {
  1459. // Infer a regular object was supplied
  1460. for (const key of Object.keys(fields)) {
  1461. fields = translate(key, fields[key]);
  1462. if (key[0] === '$') {
  1463. if (Array.isArray(fields[key])) {
  1464. for (const i in fields[key]) {
  1465. // Recursively translate nested queries
  1466. fields[key][i] = this.translateAliases(fields[key][i]);
  1467. }
  1468. }
  1469. }
  1470. }
  1471. }
  1472. return fields;
  1473. } else {
  1474. // Don't know typeof fields
  1475. return fields;
  1476. }
  1477. };
  1478. /**
  1479. * Removes all documents that match `conditions` from the collection.
  1480. * To remove just the first document that matches `conditions`, set the `single`
  1481. * option to true.
  1482. *
  1483. * ####Example:
  1484. *
  1485. * const res = await Character.remove({ name: 'Eddard Stark' });
  1486. * res.deletedCount; // Number of documents removed
  1487. *
  1488. * ####Note:
  1489. *
  1490. * This method sends a remove command directly to MongoDB, no Mongoose documents
  1491. * are involved. Because no Mongoose documents are involved, Mongoose does
  1492. * not execute [document middleware](/docs/middleware.html#types-of-middleware).
  1493. *
  1494. * @param {Object} conditions
  1495. * @param {Function} [callback]
  1496. * @return {Query}
  1497. * @api public
  1498. */
  1499. Model.remove = function remove(conditions, callback) {
  1500. if (typeof conditions === 'function') {
  1501. callback = conditions;
  1502. conditions = {};
  1503. }
  1504. // get the mongodb collection object
  1505. const mq = new this.Query({}, {}, this, this.collection);
  1506. callback = this.$wrapCallback(callback);
  1507. return mq.remove(conditions, callback);
  1508. };
  1509. /**
  1510. * Deletes the first document that matches `conditions` from the collection.
  1511. * Behaves like `remove()`, but deletes at most one document regardless of the
  1512. * `single` option.
  1513. *
  1514. * ####Example:
  1515. *
  1516. * Character.deleteOne({ name: 'Eddard Stark' }, function (err) {});
  1517. *
  1518. * ####Note:
  1519. *
  1520. * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks.
  1521. *
  1522. * @param {Object} conditions
  1523. * @param {Function} [callback]
  1524. * @return {Query}
  1525. * @api public
  1526. */
  1527. Model.deleteOne = function deleteOne(conditions, callback) {
  1528. if (typeof conditions === 'function') {
  1529. callback = conditions;
  1530. conditions = {};
  1531. }
  1532. // get the mongodb collection object
  1533. const mq = new this.Query(conditions, {}, this, this.collection);
  1534. callback = this.$wrapCallback(callback);
  1535. return mq.deleteOne(callback);
  1536. };
  1537. /**
  1538. * Deletes all of the documents that match `conditions` from the collection.
  1539. * Behaves like `remove()`, but deletes all documents that match `conditions`
  1540. * regardless of the `single` option.
  1541. *
  1542. * ####Example:
  1543. *
  1544. * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {});
  1545. *
  1546. * ####Note:
  1547. *
  1548. * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks.
  1549. *
  1550. * @param {Object} conditions
  1551. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1552. * @param {Function} [callback]
  1553. * @return {Query}
  1554. * @api public
  1555. */
  1556. Model.deleteMany = function deleteMany(conditions, options, callback) {
  1557. if (typeof conditions === 'function') {
  1558. callback = conditions;
  1559. conditions = {};
  1560. options = null;
  1561. }
  1562. else if (typeof options === 'function') {
  1563. callback = options;
  1564. options = null;
  1565. }
  1566. // get the mongodb collection object
  1567. const mq = new this.Query(conditions, {}, this, this.collection);
  1568. mq.setOptions(options);
  1569. if (callback) {
  1570. callback = this.$wrapCallback(callback);
  1571. }
  1572. return mq.deleteMany(callback);
  1573. };
  1574. /**
  1575. * Finds documents
  1576. *
  1577. * The `conditions` are cast to their respective SchemaTypes before the command is sent.
  1578. *
  1579. * ####Examples:
  1580. *
  1581. * // named john and at least 18
  1582. * MyModel.find({ name: 'john', age: { $gte: 18 }});
  1583. *
  1584. * // executes, passing results to callback
  1585. * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
  1586. *
  1587. * // executes, name LIKE john and only selecting the "name" and "friends" fields
  1588. * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
  1589. *
  1590. * // passing options
  1591. * MyModel.find({ name: /john/i }, null, { skip: 10 })
  1592. *
  1593. * // passing options and executes
  1594. * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
  1595. *
  1596. * // executing a query explicitly
  1597. * var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
  1598. * query.exec(function (err, docs) {});
  1599. *
  1600. * // using the promise returned from executing a query
  1601. * var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
  1602. * var promise = query.exec();
  1603. * promise.addBack(function (err, docs) {});
  1604. *
  1605. * @param {Object} conditions
  1606. * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  1607. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1608. * @param {Function} [callback]
  1609. * @return {Query}
  1610. * @see field selection #query_Query-select
  1611. * @see promise #promise-js
  1612. * @api public
  1613. */
  1614. Model.find = function find(conditions, projection, options, callback) {
  1615. if (typeof conditions === 'function') {
  1616. callback = conditions;
  1617. conditions = {};
  1618. projection = null;
  1619. options = null;
  1620. } else if (typeof projection === 'function') {
  1621. callback = projection;
  1622. projection = null;
  1623. options = null;
  1624. } else if (typeof options === 'function') {
  1625. callback = options;
  1626. options = null;
  1627. }
  1628. const mq = new this.Query({}, {}, this, this.collection);
  1629. mq.select(projection);
  1630. mq.setOptions(options);
  1631. if (this.schema.discriminatorMapping &&
  1632. this.schema.discriminatorMapping.isRoot &&
  1633. mq.selectedInclusively()) {
  1634. // Need to select discriminator key because original schema doesn't have it
  1635. mq.select(this.schema.options.discriminatorKey);
  1636. }
  1637. if (callback) {
  1638. callback = this.$wrapCallback(callback);
  1639. }
  1640. return mq.find(conditions, callback);
  1641. };
  1642. /**
  1643. * Finds a single document by its _id field. `findById(id)` is almost*
  1644. * equivalent to `findOne({ _id: id })`. If you want to query by a document's
  1645. * `_id`, use `findById()` instead of `findOne()`.
  1646. *
  1647. * The `id` is cast based on the Schema before sending the command.
  1648. *
  1649. * This function triggers the following middleware.
  1650. *
  1651. * - `findOne()`
  1652. *
  1653. * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see
  1654. * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent
  1655. * to `findOne({})` and return arbitrary documents. However, mongoose
  1656. * translates `findById(undefined)` into `findOne({ _id: null })`.
  1657. *
  1658. * ####Example:
  1659. *
  1660. * // find adventure by id and execute
  1661. * Adventure.findById(id, function (err, adventure) {});
  1662. *
  1663. * // same as above
  1664. * Adventure.findById(id).exec(callback);
  1665. *
  1666. * // select only the adventures name and length
  1667. * Adventure.findById(id, 'name length', function (err, adventure) {});
  1668. *
  1669. * // same as above
  1670. * Adventure.findById(id, 'name length').exec(callback);
  1671. *
  1672. * // include all properties except for `length`
  1673. * Adventure.findById(id, '-length').exec(function (err, adventure) {});
  1674. *
  1675. * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
  1676. * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});
  1677. *
  1678. * // same as above
  1679. * Adventure.findById(id, 'name').lean().exec(function (err, doc) {});
  1680. *
  1681. * @param {Object|String|Number} id value of `_id` to query by
  1682. * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  1683. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1684. * @param {Function} [callback]
  1685. * @return {Query}
  1686. * @see field selection #query_Query-select
  1687. * @see lean queries /docs/tutorials/lean.html
  1688. * @api public
  1689. */
  1690. Model.findById = function findById(id, projection, options, callback) {
  1691. if (typeof id === 'undefined') {
  1692. id = null;
  1693. }
  1694. if (callback) {
  1695. callback = this.$wrapCallback(callback);
  1696. }
  1697. return this.findOne({_id: id}, projection, options, callback);
  1698. };
  1699. /**
  1700. * Finds one document.
  1701. *
  1702. * The `conditions` are cast to their respective SchemaTypes before the command is sent.
  1703. *
  1704. * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
  1705. * mongoose will send an empty `findOne` command to MongoDB, which will return
  1706. * an arbitrary document. If you're querying by `_id`, use `findById()` instead.
  1707. *
  1708. * ####Example:
  1709. *
  1710. * // find one iphone adventures - iphone adventures??
  1711. * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});
  1712. *
  1713. * // same as above
  1714. * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});
  1715. *
  1716. * // select only the adventures name
  1717. * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});
  1718. *
  1719. * // same as above
  1720. * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});
  1721. *
  1722. * // specify options, in this case lean
  1723. * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);
  1724. *
  1725. * // same as above
  1726. * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);
  1727. *
  1728. * // chaining findOne queries (same as above)
  1729. * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);
  1730. *
  1731. * @param {Object} [conditions]
  1732. * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  1733. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1734. * @param {Function} [callback]
  1735. * @return {Query}
  1736. * @see field selection #query_Query-select
  1737. * @see lean queries /docs/tutorials/lean.html
  1738. * @api public
  1739. */
  1740. Model.findOne = function findOne(conditions, projection, options, callback) {
  1741. if (typeof options === 'function') {
  1742. callback = options;
  1743. options = null;
  1744. } else if (typeof projection === 'function') {
  1745. callback = projection;
  1746. projection = null;
  1747. options = null;
  1748. } else if (typeof conditions === 'function') {
  1749. callback = conditions;
  1750. conditions = {};
  1751. projection = null;
  1752. options = null;
  1753. }
  1754. // get the mongodb collection object
  1755. const mq = new this.Query({}, {}, this, this.collection);
  1756. mq.select(projection);
  1757. mq.setOptions(options);
  1758. if (this.schema.discriminatorMapping &&
  1759. this.schema.discriminatorMapping.isRoot &&
  1760. mq.selectedInclusively()) {
  1761. mq.select(this.schema.options.discriminatorKey);
  1762. }
  1763. if (callback) {
  1764. callback = this.$wrapCallback(callback);
  1765. }
  1766. return mq.findOne(conditions, callback);
  1767. };
  1768. /**
  1769. * Estimates the number of documents in the MongoDB collection. Faster than
  1770. * using `countDocuments()` for large collections because
  1771. * `estimatedDocumentCount()` uses collection metadata rather than scanning
  1772. * the entire collection.
  1773. *
  1774. * ####Example:
  1775. *
  1776. * const numAdventures = Adventure.estimatedDocumentCount();
  1777. *
  1778. * @param {Object} [options]
  1779. * @param {Function} [callback]
  1780. * @return {Query}
  1781. * @api public
  1782. */
  1783. Model.estimatedDocumentCount = function estimatedDocumentCount(options, callback) {
  1784. // get the mongodb collection object
  1785. const mq = new this.Query({}, {}, this, this.collection);
  1786. callback = this.$wrapCallback(callback);
  1787. return mq.estimatedDocumentCount(options, callback);
  1788. };
  1789. /**
  1790. * Counts number of documents matching `filter` in a database collection.
  1791. *
  1792. * ####Example:
  1793. *
  1794. * Adventure.countDocuments({ type: 'jungle' }, function (err, count) {
  1795. * console.log('there are %d jungle adventures', count);
  1796. * });
  1797. *
  1798. * If you want to count all documents in a large collection,
  1799. * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount)
  1800. * instead. If you call `countDocuments({})`, MongoDB will always execute
  1801. * a full collection scan and **not** use any indexes.
  1802. *
  1803. * The `countDocuments()` function is similar to `count()`, but there are a
  1804. * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
  1805. * Below are the operators that `count()` supports but `countDocuments()` does not,
  1806. * and the suggested replacement:
  1807. *
  1808. * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/)
  1809. * - `$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)
  1810. * - `$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)
  1811. *
  1812. * @param {Object} filter
  1813. * @param {Function} [callback]
  1814. * @return {Query}
  1815. * @api public
  1816. */
  1817. Model.countDocuments = function countDocuments(conditions, callback) {
  1818. if (typeof conditions === 'function') {
  1819. callback = conditions;
  1820. conditions = {};
  1821. }
  1822. // get the mongodb collection object
  1823. const mq = new this.Query({}, {}, this, this.collection);
  1824. callback = this.$wrapCallback(callback);
  1825. return mq.countDocuments(conditions, callback);
  1826. };
  1827. /**
  1828. * Counts number of documents that match `filter` in a database collection.
  1829. *
  1830. * This method is deprecated. If you want to count the number of documents in
  1831. * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount)
  1832. * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead.
  1833. *
  1834. * ####Example:
  1835. *
  1836. * Adventure.count({ type: 'jungle' }, function (err, count) {
  1837. * if (err) ..
  1838. * console.log('there are %d jungle adventures', count);
  1839. * });
  1840. *
  1841. * @deprecated
  1842. * @param {Object} filter
  1843. * @param {Function} [callback]
  1844. * @return {Query}
  1845. * @api public
  1846. */
  1847. Model.count = function count(conditions, callback) {
  1848. if (typeof conditions === 'function') {
  1849. callback = conditions;
  1850. conditions = {};
  1851. }
  1852. // get the mongodb collection object
  1853. const mq = new this.Query({}, {}, this, this.collection);
  1854. if (callback) {
  1855. callback = this.$wrapCallback(callback);
  1856. }
  1857. return mq.count(conditions, callback);
  1858. };
  1859. /**
  1860. * Creates a Query for a `distinct` operation.
  1861. *
  1862. * Passing a `callback` executes the query.
  1863. *
  1864. * ####Example
  1865. *
  1866. * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
  1867. * if (err) return handleError(err);
  1868. *
  1869. * assert(Array.isArray(result));
  1870. * console.log('unique urls with more than 100 clicks', result);
  1871. * })
  1872. *
  1873. * var query = Link.distinct('url');
  1874. * query.exec(callback);
  1875. *
  1876. * @param {String} field
  1877. * @param {Object} [conditions] optional
  1878. * @param {Function} [callback]
  1879. * @return {Query}
  1880. * @api public
  1881. */
  1882. Model.distinct = function distinct(field, conditions, callback) {
  1883. // get the mongodb collection object
  1884. const mq = new this.Query({}, {}, this, this.collection);
  1885. if (typeof conditions === 'function') {
  1886. callback = conditions;
  1887. conditions = {};
  1888. }
  1889. if (callback) {
  1890. callback = this.$wrapCallback(callback);
  1891. }
  1892. return mq.distinct(field, conditions, callback);
  1893. };
  1894. /**
  1895. * Creates a Query, applies the passed conditions, and returns the Query.
  1896. *
  1897. * For example, instead of writing:
  1898. *
  1899. * User.find({age: {$gte: 21, $lte: 65}}, callback);
  1900. *
  1901. * we can instead write:
  1902. *
  1903. * User.where('age').gte(21).lte(65).exec(callback);
  1904. *
  1905. * Since the Query class also supports `where` you can continue chaining
  1906. *
  1907. * User
  1908. * .where('age').gte(21).lte(65)
  1909. * .where('name', /^b/i)
  1910. * ... etc
  1911. *
  1912. * @param {String} path
  1913. * @param {Object} [val] optional value
  1914. * @return {Query}
  1915. * @api public
  1916. */
  1917. Model.where = function where(path, val) {
  1918. void val; // eslint
  1919. // get the mongodb collection object
  1920. const mq = new this.Query({}, {}, this, this.collection).find({});
  1921. return mq.where.apply(mq, arguments);
  1922. };
  1923. /**
  1924. * Creates a `Query` and specifies a `$where` condition.
  1925. *
  1926. * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.
  1927. *
  1928. * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});
  1929. *
  1930. * @param {String|Function} argument is a javascript string or anonymous function
  1931. * @method $where
  1932. * @memberOf Model
  1933. * @return {Query}
  1934. * @see Query.$where #query_Query-%24where
  1935. * @api public
  1936. */
  1937. Model.$where = function $where() {
  1938. const mq = new this.Query({}, {}, this, this.collection).find({});
  1939. return mq.$where.apply(mq, arguments);
  1940. };
  1941. /**
  1942. * Issues a mongodb findAndModify update command.
  1943. *
  1944. * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned.
  1945. *
  1946. * ####Options:
  1947. *
  1948. * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  1949. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  1950. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
  1951. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  1952. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  1953. * - `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.
  1954. * - `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/).
  1955. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  1956. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  1957. *
  1958. * ####Examples:
  1959. *
  1960. * A.findOneAndUpdate(conditions, update, options, callback) // executes
  1961. * A.findOneAndUpdate(conditions, update, options) // returns Query
  1962. * A.findOneAndUpdate(conditions, update, callback) // executes
  1963. * A.findOneAndUpdate(conditions, update) // returns Query
  1964. * A.findOneAndUpdate() // returns Query
  1965. *
  1966. * ####Note:
  1967. *
  1968. * All top level update keys which are not `atomic` operation names are treated as set operations:
  1969. *
  1970. * ####Example:
  1971. *
  1972. * var query = { name: 'borne' };
  1973. * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)
  1974. *
  1975. * // is sent as
  1976. * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)
  1977. *
  1978. * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`.
  1979. *
  1980. * ####Note:
  1981. *
  1982. * Values are cast to their appropriate types when using the findAndModify helpers.
  1983. * However, the below are not executed by default.
  1984. *
  1985. * - defaults. Use the `setDefaultsOnInsert` option to override.
  1986. *
  1987. * `findAndModify` helpers support limited validation. You can
  1988. * enable these by setting the `runValidators` options,
  1989. * respectively.
  1990. *
  1991. * If you need full-fledged validation, use the traditional approach of first
  1992. * retrieving the document.
  1993. *
  1994. * Model.findById(id, function (err, doc) {
  1995. * if (err) ..
  1996. * doc.name = 'jason bourne';
  1997. * doc.save(callback);
  1998. * });
  1999. *
  2000. * @param {Object} [conditions]
  2001. * @param {Object} [update]
  2002. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2003. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html).
  2004. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2005. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  2006. * @param {Function} [callback]
  2007. * @return {Query}
  2008. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2009. * @api public
  2010. */
  2011. Model.findOneAndUpdate = function(conditions, update, options, callback) {
  2012. if (typeof options === 'function') {
  2013. callback = options;
  2014. options = null;
  2015. } else if (arguments.length === 1) {
  2016. if (typeof conditions === 'function') {
  2017. const msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n'
  2018. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n'
  2019. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n'
  2020. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n'
  2021. + ' ' + this.modelName + '.findOneAndUpdate(update)\n'
  2022. + ' ' + this.modelName + '.findOneAndUpdate()\n';
  2023. throw new TypeError(msg);
  2024. }
  2025. update = conditions;
  2026. conditions = undefined;
  2027. }
  2028. if (callback) {
  2029. callback = this.$wrapCallback(callback);
  2030. }
  2031. let fields;
  2032. if (options) {
  2033. fields = options.fields || options.projection;
  2034. }
  2035. update = utils.clone(update, {
  2036. depopulate: true,
  2037. _isNested: true
  2038. });
  2039. _decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey);
  2040. const mq = new this.Query({}, {}, this, this.collection);
  2041. mq.select(fields);
  2042. return mq.findOneAndUpdate(conditions, update, options, callback);
  2043. };
  2044. /*!
  2045. * Decorate the update with a version key, if necessary
  2046. */
  2047. function _decorateUpdateWithVersionKey(update, options, versionKey) {
  2048. if (!versionKey || !get(options, 'upsert', false)) {
  2049. return;
  2050. }
  2051. const updatedPaths = modifiedPaths(update);
  2052. if (!updatedPaths[versionKey]) {
  2053. if (options.overwrite) {
  2054. update[versionKey] = 0;
  2055. } else {
  2056. if (!update.$setOnInsert) {
  2057. update.$setOnInsert = {};
  2058. }
  2059. update.$setOnInsert[versionKey] = 0;
  2060. }
  2061. }
  2062. }
  2063. /**
  2064. * Issues a mongodb findAndModify update command by a document's _id field.
  2065. * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`.
  2066. *
  2067. * Finds a matching document, updates it according to the `update` arg,
  2068. * passing any `options`, and returns the found document (if any) to the
  2069. * callback. The query executes if `callback` is passed.
  2070. *
  2071. * This function triggers the following middleware.
  2072. *
  2073. * - `findOneAndUpdate()`
  2074. *
  2075. * ####Options:
  2076. *
  2077. * - `new`: bool - true to return the modified document rather than the original. defaults to false
  2078. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  2079. * - `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.
  2080. * - `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/).
  2081. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2082. * - `select`: sets the document fields to return
  2083. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2084. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2085. *
  2086. * ####Examples:
  2087. *
  2088. * A.findByIdAndUpdate(id, update, options, callback) // executes
  2089. * A.findByIdAndUpdate(id, update, options) // returns Query
  2090. * A.findByIdAndUpdate(id, update, callback) // executes
  2091. * A.findByIdAndUpdate(id, update) // returns Query
  2092. * A.findByIdAndUpdate() // returns Query
  2093. *
  2094. * ####Note:
  2095. *
  2096. * All top level update keys which are not `atomic` operation names are treated as set operations:
  2097. *
  2098. * ####Example:
  2099. *
  2100. * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)
  2101. *
  2102. * // is sent as
  2103. * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback)
  2104. *
  2105. * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`.
  2106. *
  2107. * ####Note:
  2108. *
  2109. * Values are cast to their appropriate types when using the findAndModify helpers.
  2110. * However, the below are not executed by default.
  2111. *
  2112. * - defaults. Use the `setDefaultsOnInsert` option to override.
  2113. *
  2114. * `findAndModify` helpers support limited validation. You can
  2115. * enable these by setting the `runValidators` options,
  2116. * respectively.
  2117. *
  2118. * If you need full-fledged validation, use the traditional approach of first
  2119. * retrieving the document.
  2120. *
  2121. * Model.findById(id, function (err, doc) {
  2122. * if (err) ..
  2123. * doc.name = 'jason bourne';
  2124. * doc.save(callback);
  2125. * });
  2126. *
  2127. * @param {Object|Number|String} id value of `_id` to query by
  2128. * @param {Object} [update]
  2129. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2130. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html).
  2131. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2132. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  2133. * @param {Function} [callback]
  2134. * @return {Query}
  2135. * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate
  2136. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2137. * @api public
  2138. */
  2139. Model.findByIdAndUpdate = function(id, update, options, callback) {
  2140. if (callback) {
  2141. callback = this.$wrapCallback(callback);
  2142. }
  2143. if (arguments.length === 1) {
  2144. if (typeof id === 'function') {
  2145. const msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n'
  2146. + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n'
  2147. + ' ' + this.modelName + '.findByIdAndUpdate(id)\n'
  2148. + ' ' + this.modelName + '.findByIdAndUpdate()\n';
  2149. throw new TypeError(msg);
  2150. }
  2151. return this.findOneAndUpdate({_id: id}, undefined);
  2152. }
  2153. // if a model is passed in instead of an id
  2154. if (id instanceof Document) {
  2155. id = id._id;
  2156. }
  2157. return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback);
  2158. };
  2159. /**
  2160. * Issue a MongoDB `findOneAndDelete()` command.
  2161. *
  2162. * Finds a matching document, removes it, and passes the found document
  2163. * (if any) to the callback.
  2164. *
  2165. * Executes the query if `callback` is passed.
  2166. *
  2167. * This function triggers the following middleware.
  2168. *
  2169. * - `findOneAndDelete()`
  2170. *
  2171. * This function differs slightly from `Model.findOneAndRemove()` in that
  2172. * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/),
  2173. * as opposed to a `findOneAndDelete()` command. For most mongoose use cases,
  2174. * this distinction is purely pedantic. You should use `findOneAndDelete()`
  2175. * unless you have a good reason not to.
  2176. *
  2177. * ####Options:
  2178. *
  2179. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2180. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2181. * - `select`: sets the document fields to return
  2182. * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
  2183. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2184. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2185. *
  2186. * ####Examples:
  2187. *
  2188. * A.findOneAndDelete(conditions, options, callback) // executes
  2189. * A.findOneAndDelete(conditions, options) // return Query
  2190. * A.findOneAndDelete(conditions, callback) // executes
  2191. * A.findOneAndDelete(conditions) // returns Query
  2192. * A.findOneAndDelete() // returns Query
  2193. *
  2194. * Values are cast to their appropriate types when using the findAndModify helpers.
  2195. * However, the below are not executed by default.
  2196. *
  2197. * - defaults. Use the `setDefaultsOnInsert` option to override.
  2198. *
  2199. * `findAndModify` helpers support limited validation. You can
  2200. * enable these by setting the `runValidators` options,
  2201. * respectively.
  2202. *
  2203. * If you need full-fledged validation, use the traditional approach of first
  2204. * retrieving the document.
  2205. *
  2206. * Model.findById(id, function (err, doc) {
  2207. * if (err) ..
  2208. * doc.name = 'jason bourne';
  2209. * doc.save(callback);
  2210. * });
  2211. *
  2212. * @param {Object} conditions
  2213. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2214. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2215. * @param {Function} [callback]
  2216. * @return {Query}
  2217. * @api public
  2218. */
  2219. Model.findOneAndDelete = function(conditions, options, callback) {
  2220. if (arguments.length === 1 && typeof conditions === 'function') {
  2221. const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n'
  2222. + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n'
  2223. + ' ' + this.modelName + '.findOneAndDelete(conditions)\n'
  2224. + ' ' + this.modelName + '.findOneAndDelete()\n';
  2225. throw new TypeError(msg);
  2226. }
  2227. if (typeof options === 'function') {
  2228. callback = options;
  2229. options = undefined;
  2230. }
  2231. if (callback) {
  2232. callback = this.$wrapCallback(callback);
  2233. }
  2234. let fields;
  2235. if (options) {
  2236. fields = options.select;
  2237. options.select = undefined;
  2238. }
  2239. const mq = new this.Query({}, {}, this, this.collection);
  2240. mq.select(fields);
  2241. return mq.findOneAndDelete(conditions, options, callback);
  2242. };
  2243. /**
  2244. * Issue a MongoDB `findOneAndDelete()` command by a document's _id field.
  2245. * In other words, `findByIdAndDelete(id)` is a shorthand for
  2246. * `findOneAndDelete({ _id: id })`.
  2247. *
  2248. * This function triggers the following middleware.
  2249. *
  2250. * - `findOneAndDelete()`
  2251. *
  2252. * @param {Object|Number|String} id value of `_id` to query by
  2253. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2254. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2255. * @param {Function} [callback]
  2256. * @return {Query}
  2257. * @see Model.findOneAndRemove #model_Model.findOneAndRemove
  2258. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2259. */
  2260. Model.findByIdAndDelete = function(id, options, callback) {
  2261. if (arguments.length === 1 && typeof id === 'function') {
  2262. const msg = 'Model.findByIdAndDelete(): First argument must not be a function.\n\n'
  2263. + ' ' + this.modelName + '.findByIdAndDelete(id, callback)\n'
  2264. + ' ' + this.modelName + '.findByIdAndDelete(id)\n'
  2265. + ' ' + this.modelName + '.findByIdAndDelete()\n';
  2266. throw new TypeError(msg);
  2267. }
  2268. if (callback) {
  2269. callback = this.$wrapCallback(callback);
  2270. }
  2271. return this.findOneAndDelete({_id: id}, options, callback);
  2272. };
  2273. /**
  2274. * Issue a MongoDB `findOneAndReplace()` command.
  2275. *
  2276. * Finds a matching document, replaces it with the provided doc, and passes the
  2277. * returned doc to the callback.
  2278. *
  2279. * Executes the query if `callback` is passed.
  2280. *
  2281. * This function triggers the following query middleware.
  2282. *
  2283. * - `findOneAndReplace()`
  2284. *
  2285. * ####Options:
  2286. *
  2287. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2288. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2289. * - `select`: sets the document fields to return
  2290. * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
  2291. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2292. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2293. *
  2294. * ####Examples:
  2295. *
  2296. * A.findOneAndReplace(conditions, options, callback) // executes
  2297. * A.findOneAndReplace(conditions, options) // return Query
  2298. * A.findOneAndReplace(conditions, callback) // executes
  2299. * A.findOneAndReplace(conditions) // returns Query
  2300. * A.findOneAndReplace() // returns Query
  2301. *
  2302. * Values are cast to their appropriate types when using the findAndModify helpers.
  2303. * However, the below are not executed by default.
  2304. *
  2305. * - defaults. Use the `setDefaultsOnInsert` option to override.
  2306. *
  2307. * @param {Object} filter Replace the first document that matches this filter
  2308. * @param {Object} [replacement] Replace with this document
  2309. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2310. * @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).
  2311. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2312. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  2313. * @param {Function} [callback]
  2314. * @return {Query}
  2315. * @api public
  2316. */
  2317. Model.findOneAndReplace = function(filter, replacement, options, callback) {
  2318. if (arguments.length === 1 && typeof filter === 'function') {
  2319. const msg = 'Model.findOneAndReplace(): First argument must not be a function.\n\n'
  2320. + ' ' + this.modelName + '.findOneAndReplace(conditions, callback)\n'
  2321. + ' ' + this.modelName + '.findOneAndReplace(conditions)\n'
  2322. + ' ' + this.modelName + '.findOneAndReplace()\n';
  2323. throw new TypeError(msg);
  2324. }
  2325. if (arguments.length === 3 && typeof options === 'function') {
  2326. callback = options;
  2327. options = replacement;
  2328. replacement = void 0;
  2329. }
  2330. if (arguments.length === 2 && typeof replacement === 'function') {
  2331. callback = replacement;
  2332. replacement = void 0;
  2333. options = void 0;
  2334. }
  2335. if (callback) {
  2336. callback = this.$wrapCallback(callback);
  2337. }
  2338. let fields;
  2339. if (options) {
  2340. fields = options.select;
  2341. options.select = undefined;
  2342. }
  2343. const mq = new this.Query({}, {}, this, this.collection);
  2344. mq.select(fields);
  2345. return mq.findOneAndReplace(filter, replacement, options, callback);
  2346. };
  2347. /**
  2348. * Issue a mongodb findAndModify remove command.
  2349. *
  2350. * Finds a matching document, removes it, passing the found document (if any) to the callback.
  2351. *
  2352. * Executes the query if `callback` is passed.
  2353. *
  2354. * This function triggers the following middleware.
  2355. *
  2356. * - `findOneAndRemove()`
  2357. *
  2358. * ####Options:
  2359. *
  2360. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2361. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2362. * - `select`: sets the document fields to return
  2363. * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
  2364. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2365. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2366. *
  2367. * ####Examples:
  2368. *
  2369. * A.findOneAndRemove(conditions, options, callback) // executes
  2370. * A.findOneAndRemove(conditions, options) // return Query
  2371. * A.findOneAndRemove(conditions, callback) // executes
  2372. * A.findOneAndRemove(conditions) // returns Query
  2373. * A.findOneAndRemove() // returns Query
  2374. *
  2375. * Values are cast to their appropriate types when using the findAndModify helpers.
  2376. * However, the below are not executed by default.
  2377. *
  2378. * - defaults. Use the `setDefaultsOnInsert` option to override.
  2379. *
  2380. * `findAndModify` helpers support limited validation. You can
  2381. * enable these by setting the `runValidators` options,
  2382. * respectively.
  2383. *
  2384. * If you need full-fledged validation, use the traditional approach of first
  2385. * retrieving the document.
  2386. *
  2387. * Model.findById(id, function (err, doc) {
  2388. * if (err) ..
  2389. * doc.name = 'jason bourne';
  2390. * doc.save(callback);
  2391. * });
  2392. *
  2393. * @param {Object} conditions
  2394. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2395. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2396. * @param {Function} [callback]
  2397. * @return {Query}
  2398. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2399. * @api public
  2400. */
  2401. Model.findOneAndRemove = function(conditions, options, callback) {
  2402. if (arguments.length === 1 && typeof conditions === 'function') {
  2403. const msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n'
  2404. + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n'
  2405. + ' ' + this.modelName + '.findOneAndRemove(conditions)\n'
  2406. + ' ' + this.modelName + '.findOneAndRemove()\n';
  2407. throw new TypeError(msg);
  2408. }
  2409. if (typeof options === 'function') {
  2410. callback = options;
  2411. options = undefined;
  2412. }
  2413. if (callback) {
  2414. callback = this.$wrapCallback(callback);
  2415. }
  2416. let fields;
  2417. if (options) {
  2418. fields = options.select;
  2419. options.select = undefined;
  2420. }
  2421. const mq = new this.Query({}, {}, this, this.collection);
  2422. mq.select(fields);
  2423. return mq.findOneAndRemove(conditions, options, callback);
  2424. };
  2425. /**
  2426. * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`.
  2427. *
  2428. * Finds a matching document, removes it, passing the found document (if any) to the callback.
  2429. *
  2430. * Executes the query if `callback` is passed.
  2431. *
  2432. * This function triggers the following middleware.
  2433. *
  2434. * - `findOneAndRemove()`
  2435. *
  2436. * ####Options:
  2437. *
  2438. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2439. * - `select`: sets the document fields to return
  2440. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2441. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2442. *
  2443. * ####Examples:
  2444. *
  2445. * A.findByIdAndRemove(id, options, callback) // executes
  2446. * A.findByIdAndRemove(id, options) // return Query
  2447. * A.findByIdAndRemove(id, callback) // executes
  2448. * A.findByIdAndRemove(id) // returns Query
  2449. * A.findByIdAndRemove() // returns Query
  2450. *
  2451. * @param {Object|Number|String} id value of `_id` to query by
  2452. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2453. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2454. * @param {Function} [callback]
  2455. * @return {Query}
  2456. * @see Model.findOneAndRemove #model_Model.findOneAndRemove
  2457. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2458. */
  2459. Model.findByIdAndRemove = function(id, options, callback) {
  2460. if (arguments.length === 1 && typeof id === 'function') {
  2461. const msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n'
  2462. + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n'
  2463. + ' ' + this.modelName + '.findByIdAndRemove(id)\n'
  2464. + ' ' + this.modelName + '.findByIdAndRemove()\n';
  2465. throw new TypeError(msg);
  2466. }
  2467. if (callback) {
  2468. callback = this.$wrapCallback(callback);
  2469. }
  2470. return this.findOneAndRemove({_id: id}, options, callback);
  2471. };
  2472. /**
  2473. * Shortcut for saving one or more documents to the database.
  2474. * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in
  2475. * docs.
  2476. *
  2477. * This function triggers the following middleware.
  2478. *
  2479. * - `save()`
  2480. *
  2481. * ####Example:
  2482. *
  2483. * // pass a spread of docs and a callback
  2484. * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
  2485. * if (err) // ...
  2486. * });
  2487. *
  2488. * // pass an array of docs
  2489. * var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
  2490. * Candy.create(array, function (err, candies) {
  2491. * if (err) // ...
  2492. *
  2493. * var jellybean = candies[0];
  2494. * var snickers = candies[1];
  2495. * // ...
  2496. * });
  2497. *
  2498. * // callback is optional; use the returned promise if you like:
  2499. * var promise = Candy.create({ type: 'jawbreaker' });
  2500. * promise.then(function (jawbreaker) {
  2501. * // ...
  2502. * })
  2503. *
  2504. * @param {Array|Object} docs Documents to insert, as a spread or array
  2505. * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread.
  2506. * @param {Function} [callback] callback
  2507. * @return {Promise}
  2508. * @api public
  2509. */
  2510. Model.create = function create(doc, options, callback) {
  2511. let args;
  2512. let cb;
  2513. const discriminatorKey = this.schema.options.discriminatorKey;
  2514. if (Array.isArray(doc)) {
  2515. args = doc;
  2516. cb = typeof options === 'function' ? options : callback;
  2517. options = options != null && typeof options === 'object' ? options : {};
  2518. } else {
  2519. const last = arguments[arguments.length - 1];
  2520. options = {};
  2521. // Handle falsy callbacks re: #5061
  2522. if (typeof last === 'function' || !last) {
  2523. cb = last;
  2524. args = utils.args(arguments, 0, arguments.length - 1);
  2525. } else {
  2526. args = utils.args(arguments);
  2527. }
  2528. if (args.length === 2 &&
  2529. args[0] != null &&
  2530. args[1] != null &&
  2531. args[0].session == null &&
  2532. last.session != null &&
  2533. last.session.constructor.name === 'ClientSession' &&
  2534. !this.schema.path('session')) {
  2535. // Probably means the user is running into the common mistake of trying
  2536. // to use a spread to specify options, see gh-7535
  2537. console.warn('WARNING: to pass a `session` to `Model.create()` in ' +
  2538. 'Mongoose, you **must** pass an array as the first argument. See: ' +
  2539. 'https://mongoosejs.com/docs/api.html#model_Model.create');
  2540. }
  2541. }
  2542. if (cb) {
  2543. cb = this.$wrapCallback(cb);
  2544. }
  2545. return utils.promiseOrCallback(cb, cb => {
  2546. if (args.length === 0) {
  2547. return cb(null);
  2548. }
  2549. const toExecute = [];
  2550. let firstError;
  2551. args.forEach(doc => {
  2552. toExecute.push(callback => {
  2553. const Model = this.discriminators && doc[discriminatorKey] != null ?
  2554. this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this, doc[discriminatorKey]) :
  2555. this;
  2556. if (Model == null) {
  2557. throw new Error(`Discriminator "${doc[discriminatorKey]}" not ` +
  2558. `found for model "${this.modelName}"`);
  2559. }
  2560. let toSave = doc;
  2561. const callbackWrapper = (error, doc) => {
  2562. if (error) {
  2563. if (!firstError) {
  2564. firstError = error;
  2565. }
  2566. return callback(null, { error: error });
  2567. }
  2568. callback(null, { doc: doc });
  2569. };
  2570. if (!(toSave instanceof Model)) {
  2571. try {
  2572. toSave = new Model(toSave);
  2573. } catch (error) {
  2574. return callbackWrapper(error);
  2575. }
  2576. }
  2577. // Make sure session is available in middleware
  2578. if (options.session != null) {
  2579. toSave.$session(options.session);
  2580. }
  2581. toSave.save(options, callbackWrapper);
  2582. });
  2583. });
  2584. parallel(toExecute, (error, res) => {
  2585. const savedDocs = [];
  2586. const len = res.length;
  2587. for (let i = 0; i < len; ++i) {
  2588. if (res[i].doc) {
  2589. savedDocs.push(res[i].doc);
  2590. }
  2591. }
  2592. if (firstError) {
  2593. return cb(firstError, savedDocs);
  2594. }
  2595. if (doc instanceof Array) {
  2596. cb(null, savedDocs);
  2597. } else {
  2598. cb.apply(this, [null].concat(savedDocs));
  2599. }
  2600. });
  2601. }, this.events);
  2602. };
  2603. /**
  2604. * _Requires a replica set running MongoDB >= 3.6.0._ Watches the
  2605. * underlying collection for changes using
  2606. * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/).
  2607. *
  2608. * This function does **not** trigger any middleware. In particular, it
  2609. * does **not** trigger aggregate middleware.
  2610. *
  2611. * The ChangeStream object is an event emitter that emits the following events:
  2612. *
  2613. * - 'change': A change occurred, see below example
  2614. * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates.
  2615. * - 'end': Emitted if the underlying stream is closed
  2616. * - 'close': Emitted if the underlying stream is closed
  2617. *
  2618. * ####Example:
  2619. *
  2620. * const doc = await Person.create({ name: 'Ned Stark' });
  2621. * const changeStream = Person.watch().on('change', change => console.log(change));
  2622. * // Will print from the above `console.log()`:
  2623. * // { _id: { _data: ... },
  2624. * // operationType: 'delete',
  2625. * // ns: { db: 'mydb', coll: 'Person' },
  2626. * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } }
  2627. * await doc.remove();
  2628. *
  2629. * @param {Array} [pipeline]
  2630. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch)
  2631. * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter
  2632. * @api public
  2633. */
  2634. Model.watch = function(pipeline, options) {
  2635. return new ChangeStream(this, pipeline, options);
  2636. };
  2637. /**
  2638. * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
  2639. * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
  2640. * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
  2641. *
  2642. * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`.
  2643. *
  2644. * This function does not trigger any middleware.
  2645. *
  2646. * ####Example:
  2647. *
  2648. * const session = await Person.startSession();
  2649. * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
  2650. * await doc.remove();
  2651. * // `doc` will always be null, even if reading from a replica set
  2652. * // secondary. Without causal consistency, it is possible to
  2653. * // get a doc back from the below query if the query reads from a
  2654. * // secondary that is experiencing replication lag.
  2655. * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
  2656. *
  2657. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
  2658. * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
  2659. * @param {Function} [callback]
  2660. * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
  2661. * @api public
  2662. */
  2663. Model.startSession = function() {
  2664. return this.db.startSession.apply(this.db, arguments);
  2665. };
  2666. /**
  2667. * Shortcut for validating an array of documents and inserting them into
  2668. * MongoDB if they're all valid. This function is faster than `.create()`
  2669. * because it only sends one operation to the server, rather than one for each
  2670. * document.
  2671. *
  2672. * Mongoose always validates each document **before** sending `insertMany`
  2673. * to MongoDB. So if one document has a validation error, no documents will
  2674. * be saved, unless you set
  2675. * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling).
  2676. *
  2677. * This function does **not** trigger save middleware.
  2678. *
  2679. * This function triggers the following middleware.
  2680. *
  2681. * - `insertMany()`
  2682. *
  2683. * ####Example:
  2684. *
  2685. * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
  2686. * Movies.insertMany(arr, function(error, docs) {});
  2687. *
  2688. * @param {Array|Object|*} doc(s)
  2689. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany)
  2690. * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`.
  2691. * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`.
  2692. * @param {Function} [callback] callback
  2693. * @return {Promise}
  2694. * @api public
  2695. */
  2696. Model.insertMany = function(arr, options, callback) {
  2697. if (typeof options === 'function') {
  2698. callback = options;
  2699. options = null;
  2700. }
  2701. return utils.promiseOrCallback(callback, cb => {
  2702. this.$__insertMany(arr, options, cb);
  2703. }, this.events);
  2704. };
  2705. /*!
  2706. * ignore
  2707. */
  2708. Model.$__insertMany = function(arr, options, callback) {
  2709. const _this = this;
  2710. if (typeof options === 'function') {
  2711. callback = options;
  2712. options = null;
  2713. }
  2714. if (callback) {
  2715. callback = this.$wrapCallback(callback);
  2716. }
  2717. callback = callback || utils.noop;
  2718. options = options || {};
  2719. const limit = get(options, 'limit', 1000);
  2720. const rawResult = get(options, 'rawResult', false);
  2721. const ordered = get(options, 'ordered', true);
  2722. if (!Array.isArray(arr)) {
  2723. arr = [arr];
  2724. }
  2725. const toExecute = [];
  2726. const validationErrors = [];
  2727. arr.forEach(function(doc) {
  2728. toExecute.push(function(callback) {
  2729. if (!(doc instanceof _this)) {
  2730. doc = new _this(doc);
  2731. }
  2732. doc.validate({ __noPromise: true }, function(error) {
  2733. if (error) {
  2734. // Option `ordered` signals that insert should be continued after reaching
  2735. // a failing insert. Therefore we delegate "null", meaning the validation
  2736. // failed. It's up to the next function to filter out all failed models
  2737. if (ordered === false) {
  2738. validationErrors.push(error);
  2739. return callback(null, null);
  2740. }
  2741. return callback(error);
  2742. }
  2743. callback(null, doc);
  2744. });
  2745. });
  2746. });
  2747. parallelLimit(toExecute, limit, function(error, docs) {
  2748. if (error) {
  2749. callback(error, null);
  2750. return;
  2751. }
  2752. // We filter all failed pre-validations by removing nulls
  2753. const docAttributes = docs.filter(function(doc) {
  2754. return doc != null;
  2755. });
  2756. // Quickly escape while there aren't any valid docAttributes
  2757. if (docAttributes.length < 1) {
  2758. callback(null, []);
  2759. return;
  2760. }
  2761. const docObjects = docAttributes.map(function(doc) {
  2762. if (doc.schema.options.versionKey) {
  2763. doc[doc.schema.options.versionKey] = 0;
  2764. }
  2765. if (doc.initializeTimestamps) {
  2766. return doc.initializeTimestamps().toObject(internalToObjectOptions);
  2767. }
  2768. return doc.toObject(internalToObjectOptions);
  2769. });
  2770. _this.collection.insertMany(docObjects, options, function(error, res) {
  2771. if (error) {
  2772. callback(error, null);
  2773. return;
  2774. }
  2775. for (let i = 0; i < docAttributes.length; ++i) {
  2776. docAttributes[i].isNew = false;
  2777. docAttributes[i].emit('isNew', false);
  2778. docAttributes[i].constructor.emit('isNew', false);
  2779. }
  2780. if (rawResult) {
  2781. if (ordered === false) {
  2782. // Decorate with mongoose validation errors in case of unordered,
  2783. // because then still do `insertMany()`
  2784. res.mongoose = {
  2785. validationErrors: validationErrors
  2786. };
  2787. }
  2788. return callback(null, res);
  2789. }
  2790. callback(null, docAttributes);
  2791. });
  2792. });
  2793. };
  2794. /**
  2795. * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`,
  2796. * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one
  2797. * command. This is faster than sending multiple independent operations (like)
  2798. * if you use `create()`) because with `bulkWrite()` there is only one round
  2799. * trip to MongoDB.
  2800. *
  2801. * Mongoose will perform casting on all operations you provide.
  2802. *
  2803. * This function does **not** trigger any middleware, not `save()` nor `update()`.
  2804. * If you need to trigger
  2805. * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead.
  2806. *
  2807. * ####Example:
  2808. *
  2809. * Character.bulkWrite([
  2810. * {
  2811. * insertOne: {
  2812. * document: {
  2813. * name: 'Eddard Stark',
  2814. * title: 'Warden of the North'
  2815. * }
  2816. * }
  2817. * },
  2818. * {
  2819. * updateOne: {
  2820. * filter: { name: 'Eddard Stark' },
  2821. * // If you were using the MongoDB driver directly, you'd need to do
  2822. * // `update: { $set: { title: ... } }` but mongoose adds $set for
  2823. * // you.
  2824. * update: { title: 'Hand of the King' }
  2825. * }
  2826. * },
  2827. * {
  2828. * deleteOne: {
  2829. * {
  2830. * filter: { name: 'Eddard Stark' }
  2831. * }
  2832. * }
  2833. * }
  2834. * ]).then(res => {
  2835. * // Prints "1 1 1"
  2836. * console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
  2837. * });
  2838. *
  2839. * The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are:
  2840. *
  2841. * - `insertOne`
  2842. * - `updateOne`
  2843. * - `updateMany`
  2844. * - `deleteOne`
  2845. * - `deleteMany`
  2846. * - `replaceOne`
  2847. *
  2848. * @param {Array} ops
  2849. * @param {Object} [ops.insertOne.document] The document to insert
  2850. * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter
  2851. * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
  2852. * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match
  2853. * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
  2854. * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
  2855. * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter
  2856. * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
  2857. * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter`
  2858. * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
  2859. * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
  2860. * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter
  2861. * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter
  2862. * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter
  2863. * @param {Object} [opts.replaceOne.replacement] The replacement document
  2864. * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter`
  2865. * @param {Object} [options]
  2866. * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.
  2867. * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html).
  2868. * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information.
  2869. * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout).
  2870. * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option)
  2871. * @param {Boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk.
  2872. * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}`
  2873. * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds
  2874. * @api public
  2875. */
  2876. Model.bulkWrite = function(ops, options, callback) {
  2877. if (typeof options === 'function') {
  2878. callback = options;
  2879. options = null;
  2880. }
  2881. if (callback) {
  2882. callback = this.$wrapCallback(callback);
  2883. }
  2884. options = options || {};
  2885. const validations = ops.map(op => castBulkWrite(this, op));
  2886. return utils.promiseOrCallback(callback, cb => {
  2887. parallel(validations, error => {
  2888. if (error) {
  2889. return cb(error);
  2890. }
  2891. this.collection.bulkWrite(ops, options, (error, res) => {
  2892. if (error) {
  2893. return cb(error);
  2894. }
  2895. cb(null, res);
  2896. });
  2897. });
  2898. }, this.events);
  2899. };
  2900. /**
  2901. * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
  2902. * The document returned has no paths marked as modified initially.
  2903. *
  2904. * ####Example:
  2905. *
  2906. * // hydrate previous data into a Mongoose document
  2907. * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
  2908. *
  2909. * @param {Object} obj
  2910. * @return {Model} document instance
  2911. * @api public
  2912. */
  2913. Model.hydrate = function(obj) {
  2914. const model = require('./queryhelpers').createModel(this, obj);
  2915. model.init(obj);
  2916. return model;
  2917. };
  2918. /**
  2919. * Updates one document in the database without returning it.
  2920. *
  2921. * This function triggers the following middleware.
  2922. *
  2923. * - `update()`
  2924. *
  2925. * ####Examples:
  2926. *
  2927. * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
  2928. *
  2929. * const res = await MyModel.update({ name: 'Tobi' }, { ferret: true });
  2930. * res.n; // Number of documents that matched `{ name: 'Tobi' }`
  2931. * // Number of documents that were changed. If every doc matched already
  2932. * // had `ferret` set to `true`, `nModified` will be 0.
  2933. * res.nModified;
  2934. *
  2935. * ####Valid options:
  2936. *
  2937. * - `safe` (boolean) safe mode (defaults to value set in schema (true))
  2938. * - `upsert` (boolean) whether to create the doc if it doesn't match (false)
  2939. * - `multi` (boolean) whether multiple documents should be updated (false)
  2940. * - `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.
  2941. * - `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/).
  2942. * - `strict` (boolean) overrides the `strict` option for this update
  2943. * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false)
  2944. *
  2945. * All `update` values are cast to their appropriate SchemaTypes before being sent.
  2946. *
  2947. * The `callback` function receives `(err, rawResponse)`.
  2948. *
  2949. * - `err` is the error if any occurred
  2950. * - `rawResponse` is the full response from Mongo
  2951. *
  2952. * ####Note:
  2953. *
  2954. * All top level keys which are not `atomic` operation names are treated as set operations:
  2955. *
  2956. * ####Example:
  2957. *
  2958. * var query = { name: 'borne' };
  2959. * Model.update(query, { name: 'jason bourne' }, options, callback);
  2960. *
  2961. * // is sent as
  2962. * Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res));
  2963. * // if overwrite option is false. If overwrite is true, sent without the $set wrapper.
  2964. *
  2965. * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`.
  2966. *
  2967. * ####Note:
  2968. *
  2969. * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error.
  2970. *
  2971. * ####Note:
  2972. *
  2973. * Although values are casted to their appropriate types when using update, the following are *not* applied:
  2974. *
  2975. * - defaults
  2976. * - setters
  2977. * - validators
  2978. * - middleware
  2979. *
  2980. * If you need those features, use the traditional approach of first retrieving the document.
  2981. *
  2982. * Model.findOne({ name: 'borne' }, function (err, doc) {
  2983. * if (err) ..
  2984. * doc.name = 'jason bourne';
  2985. * doc.save(callback);
  2986. * })
  2987. *
  2988. * @see strict http://mongoosejs.com/docs/guide.html#strict
  2989. * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output
  2990. * @param {Object} conditions
  2991. * @param {Object} doc
  2992. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2993. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2994. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  2995. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  2996. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  2997. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  2998. * @param {Function} [callback] params are (error, writeOpResult)
  2999. * @param {Function} [callback]
  3000. * @return {Query}
  3001. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3002. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3003. * @see Query docs https://mongoosejs.com/docs/queries.html
  3004. * @api public
  3005. */
  3006. Model.update = function update(conditions, doc, options, callback) {
  3007. return _update(this, 'update', conditions, doc, options, callback);
  3008. };
  3009. /**
  3010. * Same as `update()`, except MongoDB will update _all_ documents that match
  3011. * `criteria` (as opposed to just the first one) regardless of the value of
  3012. * the `multi` option.
  3013. *
  3014. * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
  3015. * and `post('updateMany')` instead.
  3016. *
  3017. * ####Example:
  3018. * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
  3019. * res.n; // Number of documents matched
  3020. * res.nModified; // Number of documents modified
  3021. *
  3022. * This function triggers the following middleware.
  3023. *
  3024. * - `updateMany()`
  3025. *
  3026. * @param {Object} conditions
  3027. * @param {Object} doc
  3028. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  3029. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3030. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3031. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3032. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  3033. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  3034. * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`.
  3035. * @return {Query}
  3036. * @see Query docs https://mongoosejs.com/docs/queries.html
  3037. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3038. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3039. * @api public
  3040. */
  3041. Model.updateMany = function updateMany(conditions, doc, options, callback) {
  3042. return _update(this, 'updateMany', conditions, doc, options, callback);
  3043. };
  3044. /**
  3045. * Same as `update()`, except it does not support the `multi` or `overwrite`
  3046. * options.
  3047. *
  3048. * - MongoDB will update _only_ the first document that matches `criteria` regardless of the value of the `multi` option.
  3049. * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`.
  3050. *
  3051. * ####Example:
  3052. * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
  3053. * res.n; // Number of documents matched
  3054. * res.nModified; // Number of documents modified
  3055. *
  3056. * This function triggers the following middleware.
  3057. *
  3058. * - `updateOne()`
  3059. *
  3060. * @param {Object} conditions
  3061. * @param {Object} doc
  3062. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  3063. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3064. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3065. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3066. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  3067. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  3068. * @param {Function} [callback] params are (error, writeOpResult)
  3069. * @return {Query}
  3070. * @see Query docs https://mongoosejs.com/docs/queries.html
  3071. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3072. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3073. * @api public
  3074. */
  3075. Model.updateOne = function updateOne(conditions, doc, options, callback) {
  3076. return _update(this, 'updateOne', conditions, doc, options, callback);
  3077. };
  3078. /**
  3079. * Same as `update()`, except MongoDB replace the existing document with the
  3080. * given document (no atomic operators like `$set`).
  3081. *
  3082. * ####Example:
  3083. * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
  3084. * res.n; // Number of documents matched
  3085. * res.nModified; // Number of documents modified
  3086. *
  3087. * This function triggers the following middleware.
  3088. *
  3089. * - `replaceOne()`
  3090. *
  3091. * @param {Object} conditions
  3092. * @param {Object} doc
  3093. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  3094. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3095. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3096. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3097. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  3098. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  3099. * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`.
  3100. * @return {Query}
  3101. * @see Query docs https://mongoosejs.com/docs/queries.html
  3102. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3103. * @return {Query}
  3104. * @api public
  3105. */
  3106. Model.replaceOne = function replaceOne(conditions, doc, options, callback) {
  3107. const versionKey = get(this, 'schema.options.versionKey', null);
  3108. if (versionKey && !doc[versionKey]) {
  3109. doc[versionKey] = 0;
  3110. }
  3111. return _update(this, 'replaceOne', conditions, doc, options, callback);
  3112. };
  3113. /*!
  3114. * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()`
  3115. * because they need to do the same thing
  3116. */
  3117. function _update(model, op, conditions, doc, options, callback) {
  3118. const mq = new model.Query({}, {}, model, model.collection);
  3119. if (callback) {
  3120. callback = model.$wrapCallback(callback);
  3121. }
  3122. // gh-2406
  3123. // make local deep copy of conditions
  3124. if (conditions instanceof Document) {
  3125. conditions = conditions.toObject();
  3126. } else {
  3127. conditions = utils.clone(conditions);
  3128. }
  3129. options = typeof options === 'function' ? options : utils.clone(options);
  3130. const versionKey = get(model, 'schema.options.versionKey', null);
  3131. _decorateUpdateWithVersionKey(doc, options, versionKey);
  3132. return mq[op](conditions, doc, options, callback);
  3133. }
  3134. /**
  3135. * Executes a mapReduce command.
  3136. *
  3137. * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options.
  3138. *
  3139. * This function does not trigger any middleware.
  3140. *
  3141. * ####Example:
  3142. *
  3143. * var o = {};
  3144. * // `map()` and `reduce()` are run on the MongoDB server, not Node.js,
  3145. * // these functions are converted to strings
  3146. * o.map = function () { emit(this.name, 1) };
  3147. * o.reduce = function (k, vals) { return vals.length };
  3148. * User.mapReduce(o, function (err, results) {
  3149. * console.log(results)
  3150. * })
  3151. *
  3152. * ####Other options:
  3153. *
  3154. * - `query` {Object} query filter object.
  3155. * - `sort` {Object} sort input objects using this key
  3156. * - `limit` {Number} max number of documents
  3157. * - `keeptemp` {Boolean, default:false} keep temporary data
  3158. * - `finalize` {Function} finalize function
  3159. * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution
  3160. * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
  3161. * - `verbose` {Boolean, default:false} provide statistics on job execution time.
  3162. * - `readPreference` {String}
  3163. * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job.
  3164. *
  3165. * ####* out options:
  3166. *
  3167. * - `{inline:1}` the results are returned in an array
  3168. * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection
  3169. * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions
  3170. * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old
  3171. *
  3172. * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](/docs/tutorials/lean.html); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).
  3173. *
  3174. * ####Example:
  3175. *
  3176. * var o = {};
  3177. * // You can also define `map()` and `reduce()` as strings if your
  3178. * // linter complains about `emit()` not being defined
  3179. * o.map = 'function () { emit(this.name, 1) }';
  3180. * o.reduce = 'function (k, vals) { return vals.length }';
  3181. * o.out = { replace: 'createdCollectionNameForResults' }
  3182. * o.verbose = true;
  3183. *
  3184. * User.mapReduce(o, function (err, model, stats) {
  3185. * console.log('map reduce took %d ms', stats.processtime)
  3186. * model.find().where('value').gt(10).exec(function (err, docs) {
  3187. * console.log(docs);
  3188. * });
  3189. * })
  3190. *
  3191. * // `mapReduce()` returns a promise. However, ES6 promises can only
  3192. * // resolve to exactly one value,
  3193. * o.resolveToObject = true;
  3194. * var promise = User.mapReduce(o);
  3195. * promise.then(function (res) {
  3196. * var model = res.model;
  3197. * var stats = res.stats;
  3198. * console.log('map reduce took %d ms', stats.processtime)
  3199. * return model.find().where('value').gt(10).exec();
  3200. * }).then(function (docs) {
  3201. * console.log(docs);
  3202. * }).then(null, handleError).end()
  3203. *
  3204. * @param {Object} o an object specifying map-reduce options
  3205. * @param {Function} [callback] optional callback
  3206. * @see http://www.mongodb.org/display/DOCS/MapReduce
  3207. * @return {Promise}
  3208. * @api public
  3209. */
  3210. Model.mapReduce = function mapReduce(o, callback) {
  3211. if (callback) {
  3212. callback = this.$wrapCallback(callback);
  3213. }
  3214. return utils.promiseOrCallback(callback, cb => {
  3215. if (!Model.mapReduce.schema) {
  3216. const opts = {noId: true, noVirtualId: true, strict: false};
  3217. Model.mapReduce.schema = new Schema({}, opts);
  3218. }
  3219. if (!o.out) o.out = {inline: 1};
  3220. if (o.verbose !== false) o.verbose = true;
  3221. o.map = String(o.map);
  3222. o.reduce = String(o.reduce);
  3223. if (o.query) {
  3224. let q = new this.Query(o.query);
  3225. q.cast(this);
  3226. o.query = q._conditions;
  3227. q = undefined;
  3228. }
  3229. this.collection.mapReduce(null, null, o, (err, res) => {
  3230. if (err) {
  3231. return cb(err);
  3232. }
  3233. if (res.collection) {
  3234. // returned a collection, convert to Model
  3235. const model = Model.compile('_mapreduce_' + res.collection.collectionName,
  3236. Model.mapReduce.schema, res.collection.collectionName, this.db,
  3237. this.base);
  3238. model._mapreduce = true;
  3239. res.model = model;
  3240. return cb(null, res);
  3241. }
  3242. cb(null, res);
  3243. });
  3244. }, this.events);
  3245. };
  3246. /**
  3247. * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection.
  3248. *
  3249. * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned.
  3250. *
  3251. * This function triggers the following middleware.
  3252. *
  3253. * - `aggregate()`
  3254. *
  3255. * ####Example:
  3256. *
  3257. * // Find the max balance of all accounts
  3258. * Users.aggregate([
  3259. * { $group: { _id: null, maxBalance: { $max: '$balance' }}},
  3260. * { $project: { _id: 0, maxBalance: 1 }}
  3261. * ]).
  3262. * then(function (res) {
  3263. * console.log(res); // [ { maxBalance: 98000 } ]
  3264. * });
  3265. *
  3266. * // Or use the aggregation pipeline builder.
  3267. * Users.aggregate().
  3268. * group({ _id: null, maxBalance: { $max: '$balance' } }).
  3269. * project('-id maxBalance').
  3270. * exec(function (err, res) {
  3271. * if (err) return handleError(err);
  3272. * console.log(res); // [ { maxBalance: 98 } ]
  3273. * });
  3274. *
  3275. * ####NOTE:
  3276. *
  3277. * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format.
  3278. * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  3279. * - Requires MongoDB >= 2.1
  3280. *
  3281. * @see Aggregate #aggregate_Aggregate
  3282. * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
  3283. * @param {Array} [pipeline] aggregation pipeline as an array of objects
  3284. * @param {Function} [callback]
  3285. * @return {Aggregate}
  3286. * @api public
  3287. */
  3288. Model.aggregate = function aggregate(pipeline, callback) {
  3289. if (arguments.length > 2 || get(pipeline, 'constructor.name') === 'Object') {
  3290. throw new Error('Mongoose 5.x disallows passing a spread of operators ' +
  3291. 'to `Model.aggregate()`. Instead of ' +
  3292. '`Model.aggregate({ $match }, { $skip })`, do ' +
  3293. '`Model.aggregate([{ $match }, { $skip }])`');
  3294. }
  3295. if (typeof pipeline === 'function') {
  3296. callback = pipeline;
  3297. pipeline = [];
  3298. }
  3299. const aggregate = new Aggregate(pipeline || []);
  3300. aggregate.model(this);
  3301. if (typeof callback === 'undefined') {
  3302. return aggregate;
  3303. }
  3304. if (callback) {
  3305. callback = this.$wrapCallback(callback);
  3306. }
  3307. aggregate.exec(callback);
  3308. return aggregate;
  3309. };
  3310. /**
  3311. * Implements `$geoSearch` functionality for Mongoose
  3312. *
  3313. * This function does not trigger any middleware
  3314. *
  3315. * ####Example:
  3316. *
  3317. * var options = { near: [10, 10], maxDistance: 5 };
  3318. * Locations.geoSearch({ type : "house" }, options, function(err, res) {
  3319. * console.log(res);
  3320. * });
  3321. *
  3322. * ####Options:
  3323. * - `near` {Array} x,y point to search for
  3324. * - `maxDistance` {Number} the maximum distance from the point near that a result can be
  3325. * - `limit` {Number} The maximum number of results to return
  3326. * - `lean` {Object|Boolean} return the raw object instead of the Mongoose Model
  3327. *
  3328. * @param {Object} conditions an object that specifies the match condition (required)
  3329. * @param {Object} options for the geoSearch, some (near, maxDistance) are required
  3330. * @param {Object|Boolean} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html).
  3331. * @param {Function} [callback] optional callback
  3332. * @return {Promise}
  3333. * @see http://docs.mongodb.org/manual/reference/command/geoSearch/
  3334. * @see http://docs.mongodb.org/manual/core/geohaystack/
  3335. * @api public
  3336. */
  3337. Model.geoSearch = function(conditions, options, callback) {
  3338. if (typeof options === 'function') {
  3339. callback = options;
  3340. options = {};
  3341. }
  3342. if (callback) {
  3343. callback = this.$wrapCallback(callback);
  3344. }
  3345. return utils.promiseOrCallback(callback, cb => {
  3346. let error;
  3347. if (conditions === undefined || !utils.isObject(conditions)) {
  3348. error = new Error('Must pass conditions to geoSearch');
  3349. } else if (!options.near) {
  3350. error = new Error('Must specify the near option in geoSearch');
  3351. } else if (!Array.isArray(options.near)) {
  3352. error = new Error('near option must be an array [x, y]');
  3353. }
  3354. if (error) {
  3355. return cb(error);
  3356. }
  3357. // send the conditions in the options object
  3358. options.search = conditions;
  3359. this.collection.geoHaystackSearch(options.near[0], options.near[1], options, (err, res) => {
  3360. if (err) {
  3361. return cb(err);
  3362. }
  3363. let count = res.results.length;
  3364. if (options.lean || count === 0) {
  3365. return cb(null, res.results);
  3366. }
  3367. const errSeen = false;
  3368. function init(err) {
  3369. if (err && !errSeen) {
  3370. return cb(err);
  3371. }
  3372. if (!--count && !errSeen) {
  3373. cb(null, res.results);
  3374. }
  3375. }
  3376. for (let i = 0; i < res.results.length; ++i) {
  3377. const temp = res.results[i];
  3378. res.results[i] = new this();
  3379. res.results[i].init(temp, {}, init);
  3380. }
  3381. });
  3382. }, this.events);
  3383. };
  3384. /**
  3385. * Populates document references.
  3386. *
  3387. * ####Available top-level options:
  3388. *
  3389. * - path: space delimited path(s) to populate
  3390. * - select: optional fields to select
  3391. * - match: optional query conditions to match
  3392. * - model: optional name of the model to use for population
  3393. * - options: optional query options like sort, limit, etc
  3394. * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default.
  3395. *
  3396. * ####Examples:
  3397. *
  3398. * // populates a single object
  3399. * User.findById(id, function (err, user) {
  3400. * var opts = [
  3401. * { path: 'company', match: { x: 1 }, select: 'name' },
  3402. * { path: 'notes', options: { limit: 10 }, model: 'override' }
  3403. * ];
  3404. *
  3405. * User.populate(user, opts, function (err, user) {
  3406. * console.log(user);
  3407. * });
  3408. * });
  3409. *
  3410. * // populates an array of objects
  3411. * User.find(match, function (err, users) {
  3412. * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }];
  3413. *
  3414. * var promise = User.populate(users, opts);
  3415. * promise.then(console.log).end();
  3416. * })
  3417. *
  3418. * // imagine a Weapon model exists with two saved documents:
  3419. * // { _id: 389, name: 'whip' }
  3420. * // { _id: 8921, name: 'boomerang' }
  3421. * // and this schema:
  3422. * // new Schema({
  3423. * // name: String,
  3424. * // weapon: { type: ObjectId, ref: 'Weapon' }
  3425. * // });
  3426. *
  3427. * var user = { name: 'Indiana Jones', weapon: 389 };
  3428. * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
  3429. * console.log(user.weapon.name); // whip
  3430. * })
  3431. *
  3432. * // populate many plain objects
  3433. * var users = [{ name: 'Indiana Jones', weapon: 389 }]
  3434. * users.push({ name: 'Batman', weapon: 8921 })
  3435. * Weapon.populate(users, { path: 'weapon' }, function (err, users) {
  3436. * users.forEach(function (user) {
  3437. * console.log('%s uses a %s', users.name, user.weapon.name)
  3438. * // Indiana Jones uses a whip
  3439. * // Batman uses a boomerang
  3440. * });
  3441. * });
  3442. * // Note that we didn't need to specify the Weapon model because
  3443. * // it is in the schema's ref
  3444. *
  3445. * @param {Document|Array} docs Either a single document or array of documents to populate.
  3446. * @param {Object} options A hash of key/val (path, options) used for population.
  3447. * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries.
  3448. * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options).
  3449. * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them.
  3450. * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object.
  3451. * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
  3452. * @return {Promise}
  3453. * @api public
  3454. */
  3455. Model.populate = function(docs, paths, callback) {
  3456. const _this = this;
  3457. if (callback) {
  3458. callback = this.$wrapCallback(callback);
  3459. }
  3460. // normalized paths
  3461. paths = utils.populate(paths);
  3462. // data that should persist across subPopulate calls
  3463. const cache = {};
  3464. return utils.promiseOrCallback(callback, cb => {
  3465. _populate(_this, docs, paths, cache, cb);
  3466. }, this.events);
  3467. };
  3468. /*!
  3469. * Populate helper
  3470. *
  3471. * @param {Model} model the model to use
  3472. * @param {Document|Array} docs Either a single document or array of documents to populate.
  3473. * @param {Object} paths
  3474. * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
  3475. * @return {Function}
  3476. * @api private
  3477. */
  3478. function _populate(model, docs, paths, cache, callback) {
  3479. let pending = paths.length;
  3480. if (pending === 0) {
  3481. return callback(null, docs);
  3482. }
  3483. // each path has its own query options and must be executed separately
  3484. let i = pending;
  3485. let path;
  3486. while (i--) {
  3487. path = paths[i];
  3488. populate(model, docs, path, next);
  3489. }
  3490. function next(err) {
  3491. if (err) {
  3492. return callback(err, null);
  3493. }
  3494. if (--pending) {
  3495. return;
  3496. }
  3497. callback(null, docs);
  3498. }
  3499. }
  3500. /*!
  3501. * Populates `docs`
  3502. */
  3503. const excludeIdReg = /\s?-_id\s?/;
  3504. const excludeIdRegGlobal = /\s?-_id\s?/g;
  3505. function populate(model, docs, options, callback) {
  3506. // normalize single / multiple docs passed
  3507. if (!Array.isArray(docs)) {
  3508. docs = [docs];
  3509. }
  3510. if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) {
  3511. return callback();
  3512. }
  3513. const modelsMap = getModelsMapForPopulate(model, docs, options);
  3514. if (modelsMap instanceof Error) {
  3515. return immediate(function() {
  3516. callback(modelsMap);
  3517. });
  3518. }
  3519. const len = modelsMap.length;
  3520. let mod;
  3521. let match;
  3522. let select;
  3523. let vals = [];
  3524. function flatten(item) {
  3525. // no need to include undefined values in our query
  3526. return undefined !== item;
  3527. }
  3528. let _remaining = len;
  3529. let hasOne = false;
  3530. for (let i = 0; i < len; ++i) {
  3531. mod = modelsMap[i];
  3532. select = mod.options.select;
  3533. match = _formatMatch(mod.match);
  3534. let ids = utils.array.flatten(mod.ids, flatten);
  3535. ids = utils.array.unique(ids);
  3536. const assignmentOpts = {};
  3537. assignmentOpts.sort = get(mod, 'options.options.sort', void 0);
  3538. assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0);
  3539. if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) {
  3540. --_remaining;
  3541. // Ensure that we set populate virtuals with count option to 0 even
  3542. // if we don't actually execute a query.
  3543. if (mod.count) {
  3544. next(mod, assignmentOpts, null, []);
  3545. }
  3546. continue;
  3547. }
  3548. hasOne = true;
  3549. if (mod.foreignField.size === 1) {
  3550. const foreignField = Array.from(mod.foreignField)[0];
  3551. if (foreignField !== '_id' || !match['_id']) {
  3552. match[foreignField] = { $in: ids };
  3553. }
  3554. } else {
  3555. const $or = [];
  3556. if (Array.isArray(match.$or)) {
  3557. match.$and = [{ $or: match.$or }, { $or: $or }];
  3558. delete match.$or;
  3559. } else {
  3560. match.$or = $or;
  3561. }
  3562. for (const foreignField of mod.foreignField) {
  3563. if (foreignField !== '_id' || !match['_id']) {
  3564. $or.push({ [foreignField]: { $in: ids } });
  3565. }
  3566. }
  3567. }
  3568. if (assignmentOpts.excludeId) {
  3569. // override the exclusion from the query so we can use the _id
  3570. // for document matching during assignment. we'll delete the
  3571. // _id back off before returning the result.
  3572. if (typeof select === 'string') {
  3573. select = select.replace(excludeIdRegGlobal, ' ');
  3574. } else {
  3575. // preserve original select conditions by copying
  3576. select = utils.object.shallowCopy(select);
  3577. delete select._id;
  3578. }
  3579. }
  3580. if (mod.options.options && mod.options.options.limit) {
  3581. assignmentOpts.originalLimit = mod.options.options.limit;
  3582. mod.options.options.limit = mod.options.options.limit * ids.length;
  3583. }
  3584. const subPopulate = utils.clone(mod.options.populate);
  3585. const query = mod.model.find(match, select, mod.options.options);
  3586. // If using count, still need the `foreignField` so we can match counts
  3587. // to documents, otherwise we would need a separate `count()` for every doc.
  3588. if (mod.count) {
  3589. for (const foreignField of mod.foreignField) {
  3590. query.select(foreignField);
  3591. }
  3592. }
  3593. // If we're doing virtual populate and projection is inclusive and foreign
  3594. // field is not selected, automatically select it because mongoose needs it.
  3595. // If projection is exclusive and client explicitly unselected the foreign
  3596. // field, that's the client's fault.
  3597. for (const foreignField of mod.foreignField) {
  3598. if (foreignField !== '_id' && query.selectedInclusively() &&
  3599. !isPathSelectedInclusive(query._fields, foreignField)) {
  3600. query.select(foreignField);
  3601. }
  3602. }
  3603. // If we need to sub-populate, call populate recursively
  3604. if (subPopulate) {
  3605. query.populate(subPopulate);
  3606. }
  3607. query.exec(next.bind(this, mod, assignmentOpts));
  3608. }
  3609. if (!hasOne) {
  3610. return callback();
  3611. }
  3612. function next(options, assignmentOpts, err, valsFromDb) {
  3613. if (mod.options.options && mod.options.options.limit) {
  3614. mod.options.options.limit = assignmentOpts.originalLimit;
  3615. }
  3616. if (err) return callback(err, null);
  3617. vals = vals.concat(valsFromDb);
  3618. _assign(null, vals, options, assignmentOpts);
  3619. if (--_remaining === 0) {
  3620. callback();
  3621. }
  3622. }
  3623. function _assign(err, vals, mod, assignmentOpts) {
  3624. if (err) {
  3625. return callback(err, null);
  3626. }
  3627. const options = mod.options;
  3628. const isVirtual = mod.isVirtual;
  3629. const justOne = mod.justOne;
  3630. let _val;
  3631. const lean = options.options && options.options.lean;
  3632. const len = vals.length;
  3633. const rawOrder = {};
  3634. const rawDocs = {};
  3635. let key;
  3636. let val;
  3637. // Clone because `assignRawDocsToIdStructure` will mutate the array
  3638. const allIds = utils.clone(mod.allIds);
  3639. // optimization:
  3640. // record the document positions as returned by
  3641. // the query result.
  3642. for (let i = 0; i < len; i++) {
  3643. val = vals[i];
  3644. if (val == null) {
  3645. continue;
  3646. }
  3647. for (const foreignField of mod.foreignField) {
  3648. _val = utils.getValue(foreignField, val);
  3649. if (Array.isArray(_val)) {
  3650. _val = utils.array.flatten(_val);
  3651. const _valLength = _val.length;
  3652. for (let j = 0; j < _valLength; ++j) {
  3653. let __val = _val[j];
  3654. if (__val instanceof Document) {
  3655. __val = __val._id;
  3656. }
  3657. key = String(__val);
  3658. if (rawDocs[key]) {
  3659. if (Array.isArray(rawDocs[key])) {
  3660. rawDocs[key].push(val);
  3661. rawOrder[key].push(i);
  3662. } else {
  3663. rawDocs[key] = [rawDocs[key], val];
  3664. rawOrder[key] = [rawOrder[key], i];
  3665. }
  3666. } else {
  3667. if (isVirtual && !justOne) {
  3668. rawDocs[key] = [val];
  3669. rawOrder[key] = [i];
  3670. } else {
  3671. rawDocs[key] = val;
  3672. rawOrder[key] = i;
  3673. }
  3674. }
  3675. }
  3676. } else {
  3677. if (_val instanceof Document) {
  3678. _val = _val._id;
  3679. }
  3680. key = String(_val);
  3681. if (rawDocs[key]) {
  3682. if (Array.isArray(rawDocs[key])) {
  3683. rawDocs[key].push(val);
  3684. rawOrder[key].push(i);
  3685. } else {
  3686. rawDocs[key] = [rawDocs[key], val];
  3687. rawOrder[key] = [rawOrder[key], i];
  3688. }
  3689. } else {
  3690. rawDocs[key] = val;
  3691. rawOrder[key] = i;
  3692. }
  3693. }
  3694. // flag each as result of population
  3695. if (lean) {
  3696. leanPopulateMap.set(val, mod.model);
  3697. } else {
  3698. val.$__.wasPopulated = true;
  3699. }
  3700. }
  3701. }
  3702. assignVals({
  3703. originalModel: model,
  3704. // If virtual, make sure to not mutate original field
  3705. rawIds: mod.isVirtual ? allIds : mod.allIds,
  3706. allIds: allIds,
  3707. foreignField: mod.foreignField,
  3708. rawDocs: rawDocs,
  3709. rawOrder: rawOrder,
  3710. docs: mod.docs,
  3711. path: options.path,
  3712. options: assignmentOpts,
  3713. justOne: mod.justOne,
  3714. isVirtual: mod.isVirtual,
  3715. allOptions: mod,
  3716. lean: lean,
  3717. virtual: mod.virtual,
  3718. count: mod.count,
  3719. match: mod.match
  3720. });
  3721. }
  3722. }
  3723. /*!
  3724. * Format `mod.match` given that it may be an array that we need to $or if
  3725. * the client has multiple docs with match functions
  3726. */
  3727. function _formatMatch(match) {
  3728. if (Array.isArray(match)) {
  3729. if (match.length > 1) {
  3730. return { $or: [].concat(match.map(m => Object.assign({}, m))) };
  3731. }
  3732. return Object.assign({}, match[0]);
  3733. }
  3734. return Object.assign({}, match);
  3735. }
  3736. function getModelsMapForPopulate(model, docs, options) {
  3737. let i;
  3738. let doc;
  3739. const len = docs.length;
  3740. const available = {};
  3741. const map = [];
  3742. const modelNameFromQuery = options.model && options.model.modelName || options.model;
  3743. let schema;
  3744. let refPath;
  3745. let Model;
  3746. let currentOptions;
  3747. let modelNames;
  3748. let modelName;
  3749. let discriminatorKey;
  3750. let modelForFindSchema;
  3751. const originalModel = options.model;
  3752. let isVirtual = false;
  3753. const modelSchema = model.schema;
  3754. for (i = 0; i < len; i++) {
  3755. doc = docs[i];
  3756. schema = getSchemaTypes(modelSchema, doc, options.path);
  3757. const isUnderneathDocArray = schema && schema.$isUnderneathDocArray;
  3758. if (isUnderneathDocArray && get(options, 'options.sort') != null) {
  3759. return new Error('Cannot populate with `sort` on path ' + options.path +
  3760. ' because it is a subproperty of a document array');
  3761. }
  3762. modelNames = null;
  3763. let isRefPath = false;
  3764. if (Array.isArray(schema)) {
  3765. for (let j = 0; j < schema.length; ++j) {
  3766. let _modelNames;
  3767. try {
  3768. const res = _getModelNames(doc, schema[j]);
  3769. _modelNames = res.modelNames;
  3770. isRefPath = res.isRefPath;
  3771. } catch (error) {
  3772. return error;
  3773. }
  3774. if (!_modelNames) {
  3775. continue;
  3776. }
  3777. modelNames = modelNames || [];
  3778. for (let x = 0; x < _modelNames.length; ++x) {
  3779. if (modelNames.indexOf(_modelNames[x]) === -1) {
  3780. modelNames.push(_modelNames[x]);
  3781. }
  3782. }
  3783. }
  3784. } else {
  3785. try {
  3786. const res = _getModelNames(doc, schema);
  3787. modelNames = res.modelNames;
  3788. isRefPath = res.isRefPath;
  3789. } catch (error) {
  3790. return error;
  3791. }
  3792. if (!modelNames) {
  3793. continue;
  3794. }
  3795. }
  3796. const virtual = getVirtual(model.schema, options.path);
  3797. let localField;
  3798. let count = false;
  3799. if (virtual && virtual.options) {
  3800. const virtualPrefix = virtual.$nestedSchemaPath ?
  3801. virtual.$nestedSchemaPath + '.' : '';
  3802. if (typeof virtual.options.localField === 'function') {
  3803. localField = virtualPrefix + virtual.options.localField.call(doc, doc);
  3804. } else {
  3805. localField = virtualPrefix + virtual.options.localField;
  3806. }
  3807. count = virtual.options.count;
  3808. } else {
  3809. localField = options.path;
  3810. }
  3811. let foreignField = virtual && virtual.options ?
  3812. virtual.options.foreignField :
  3813. '_id';
  3814. // `justOne = null` means we don't know from the schema whether the end
  3815. // result should be an array or a single doc. This can result from
  3816. // populating a POJO using `Model.populate()`
  3817. let justOne = null;
  3818. if ('justOne' in options) {
  3819. justOne = options.justOne;
  3820. } else if (virtual && virtual.options && virtual.options.ref) {
  3821. let normalizedRef;
  3822. if (typeof virtual.options.ref === 'function') {
  3823. normalizedRef = virtual.options.ref.call(doc, doc);
  3824. } else {
  3825. normalizedRef = virtual.options.ref;
  3826. }
  3827. justOne = !!virtual.options.justOne;
  3828. isVirtual = true;
  3829. if (!modelNames) {
  3830. modelNames = [].concat(normalizedRef);
  3831. }
  3832. } else if (schema && !schema[schemaMixedSymbol]) {
  3833. // Skip Mixed types because we explicitly don't do casting on those.
  3834. justOne = !schema.$isMongooseArray;
  3835. }
  3836. if (!modelNames) {
  3837. continue;
  3838. }
  3839. if (virtual && (!localField || !foreignField)) {
  3840. return new Error('If you are populating a virtual, you must set the ' +
  3841. 'localField and foreignField options');
  3842. }
  3843. options.isVirtual = isVirtual;
  3844. options.virtual = virtual;
  3845. if (typeof localField === 'function') {
  3846. localField = localField.call(doc, doc);
  3847. }
  3848. if (typeof foreignField === 'function') {
  3849. foreignField = foreignField.call(doc);
  3850. }
  3851. const localFieldPathType = modelSchema._getPathType(localField);
  3852. const localFieldPath = localFieldPathType === 'real' ? modelSchema.paths[localField] : localFieldPathType.schema;
  3853. const localFieldGetters = localFieldPath && localFieldPath.getters ? localFieldPath.getters : [];
  3854. let ret;
  3855. const _populateOptions = get(options, 'options', {});
  3856. const getters = 'getters' in _populateOptions ?
  3857. _populateOptions.getters :
  3858. options.isVirtual && get(virtual, 'options.getters', false);
  3859. if (localFieldGetters.length > 0 && getters) {
  3860. const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc);
  3861. const localFieldValue = utils.getValue(localField, doc);
  3862. if (Array.isArray(localFieldValue)) {
  3863. const localFieldHydratedValue = utils.getValue(localField.split('.').slice(0, -1), hydratedDoc);
  3864. ret = localFieldValue.map((localFieldArrVal, localFieldArrIndex) =>
  3865. localFieldPath.applyGetters(localFieldArrVal, localFieldHydratedValue[localFieldArrIndex]));
  3866. } else {
  3867. ret = localFieldPath.applyGetters(localFieldValue, hydratedDoc);
  3868. }
  3869. } else {
  3870. ret = convertTo_id(utils.getValue(localField, doc));
  3871. }
  3872. const id = String(utils.getValue(foreignField, doc));
  3873. options._docs[id] = Array.isArray(ret) ? ret.slice() : ret;
  3874. let match = get(options, 'match', null) ||
  3875. get(currentOptions, 'match', null) ||
  3876. get(options, 'virtual.options.options.match', null);
  3877. const hasMatchFunction = typeof match === 'function';
  3878. if (hasMatchFunction) {
  3879. match = match.call(doc, doc);
  3880. }
  3881. let k = modelNames.length;
  3882. while (k--) {
  3883. modelName = modelNames[k];
  3884. if (modelName == null) {
  3885. continue;
  3886. }
  3887. try {
  3888. Model = originalModel && originalModel[modelSymbol] ?
  3889. originalModel :
  3890. modelName[modelSymbol] ? modelName : model.db.model(modelName);
  3891. } catch (error) {
  3892. return error;
  3893. }
  3894. let ids = ret;
  3895. const flat = Array.isArray(ret) ? utils.array.flatten(ret) : [];
  3896. if (isRefPath && Array.isArray(ret) && flat.length === modelNames.length) {
  3897. ids = flat.filter((val, i) => modelNames[i] === modelName);
  3898. }
  3899. if (!available[modelName]) {
  3900. currentOptions = {
  3901. model: Model
  3902. };
  3903. if (isVirtual && virtual.options && virtual.options.options) {
  3904. currentOptions.options = utils.clone(virtual.options.options);
  3905. }
  3906. utils.merge(currentOptions, options);
  3907. if (schema && !discriminatorKey) {
  3908. currentOptions.model = Model;
  3909. }
  3910. options.model = Model;
  3911. available[modelName] = {
  3912. model: Model,
  3913. options: currentOptions,
  3914. match: hasMatchFunction ? [match] : match,
  3915. docs: [doc],
  3916. ids: [ids],
  3917. allIds: [ret],
  3918. localField: new Set([localField]),
  3919. foreignField: new Set([foreignField]),
  3920. justOne: justOne,
  3921. isVirtual: isVirtual,
  3922. virtual: virtual,
  3923. count: count
  3924. };
  3925. map.push(available[modelName]);
  3926. } else {
  3927. available[modelName].localField.add(localField);
  3928. available[modelName].foreignField.add(foreignField);
  3929. available[modelName].docs.push(doc);
  3930. available[modelName].ids.push(ids);
  3931. available[modelName].allIds.push(ret);
  3932. if (hasMatchFunction) {
  3933. available[modelName].match.push(match);
  3934. }
  3935. }
  3936. }
  3937. }
  3938. function _getModelNames(doc, schema) {
  3939. let modelNames;
  3940. let discriminatorKey;
  3941. let isRefPath = false;
  3942. if (schema && schema.caster) {
  3943. schema = schema.caster;
  3944. }
  3945. if (schema && schema.$isSchemaMap) {
  3946. schema = schema.$__schemaType;
  3947. }
  3948. if (!schema && model.discriminators) {
  3949. discriminatorKey = model.schema.discriminatorMapping.key;
  3950. }
  3951. refPath = schema && schema.options && schema.options.refPath;
  3952. const normalizedRefPath = normalizeRefPath(refPath, doc, options.path);
  3953. if (modelNameFromQuery) {
  3954. modelNames = [modelNameFromQuery]; // query options
  3955. } else if (normalizedRefPath) {
  3956. if (options._queryProjection != null && isPathExcluded(options._queryProjection, normalizedRefPath)) {
  3957. throw new Error('refPath `' + normalizedRefPath +
  3958. '` must not be excluded in projection, got ' +
  3959. util.inspect(options._queryProjection));
  3960. }
  3961. modelNames = utils.getValue(normalizedRefPath, doc);
  3962. if (Array.isArray(modelNames)) {
  3963. modelNames = utils.array.flatten(modelNames);
  3964. }
  3965. isRefPath = true;
  3966. } else {
  3967. let modelForCurrentDoc = model;
  3968. let schemaForCurrentDoc;
  3969. if (!schema && discriminatorKey) {
  3970. modelForFindSchema = utils.getValue(discriminatorKey, doc);
  3971. if (modelForFindSchema) {
  3972. try {
  3973. modelForCurrentDoc = model.db.model(modelForFindSchema);
  3974. } catch (error) {
  3975. return error;
  3976. }
  3977. schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path);
  3978. if (schemaForCurrentDoc && schemaForCurrentDoc.caster) {
  3979. schemaForCurrentDoc = schemaForCurrentDoc.caster;
  3980. }
  3981. }
  3982. } else {
  3983. schemaForCurrentDoc = schema;
  3984. }
  3985. const virtual = getVirtual(modelForCurrentDoc.schema, options.path);
  3986. let ref;
  3987. if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) {
  3988. modelNames = [ref];
  3989. } else if ((ref = get(virtual, 'options.ref')) != null) {
  3990. if (typeof ref === 'function') {
  3991. ref = ref.call(doc, doc);
  3992. }
  3993. // When referencing nested arrays, the ref should be an Array
  3994. // of modelNames.
  3995. if (Array.isArray(ref)) {
  3996. modelNames = ref;
  3997. } else {
  3998. modelNames = [ref];
  3999. }
  4000. isVirtual = true;
  4001. } else {
  4002. // We may have a discriminator, in which case we don't want to
  4003. // populate using the base model by default
  4004. modelNames = discriminatorKey ? null : [model.modelName];
  4005. }
  4006. }
  4007. if (!modelNames) {
  4008. return { modelNames: modelNames, isRefPath: isRefPath };
  4009. }
  4010. if (!Array.isArray(modelNames)) {
  4011. modelNames = [modelNames];
  4012. }
  4013. return { modelNames: modelNames, isRefPath: isRefPath };
  4014. }
  4015. return map;
  4016. }
  4017. /*!
  4018. * Retrieve the _id of `val` if a Document or Array of Documents.
  4019. *
  4020. * @param {Array|Document|Any} val
  4021. * @return {Array|Document|Any}
  4022. */
  4023. function convertTo_id(val) {
  4024. if (val instanceof Model) return val._id;
  4025. if (Array.isArray(val)) {
  4026. for (let i = 0; i < val.length; ++i) {
  4027. if (val[i] instanceof Model) {
  4028. val[i] = val[i]._id;
  4029. }
  4030. }
  4031. if (val.isMongooseArray && val.$schema()) {
  4032. return val.$schema().cast(val, val.$parent());
  4033. }
  4034. return [].concat(val);
  4035. }
  4036. // `populate('map')` may be an object if populating on a doc that hasn't
  4037. // been hydrated yet
  4038. if (val != null && val.constructor.name === 'Object') {
  4039. const ret = [];
  4040. for (const key of Object.keys(val)) {
  4041. ret.push(val[key]);
  4042. }
  4043. return ret;
  4044. }
  4045. // If doc has already been hydrated, e.g. `doc.populate('map').execPopulate()`
  4046. // then `val` will already be a map
  4047. if (val instanceof Map) {
  4048. return Array.from(val.values());
  4049. }
  4050. return val;
  4051. }
  4052. /*!
  4053. * Compiler utility.
  4054. *
  4055. * @param {String|Function} name model name or class extending Model
  4056. * @param {Schema} schema
  4057. * @param {String} collectionName
  4058. * @param {Connection} connection
  4059. * @param {Mongoose} base mongoose instance
  4060. */
  4061. Model.compile = function compile(name, schema, collectionName, connection, base) {
  4062. const versioningEnabled = schema.options.versionKey !== false;
  4063. if (versioningEnabled && !schema.paths[schema.options.versionKey]) {
  4064. // add versioning to top level documents only
  4065. const o = {};
  4066. o[schema.options.versionKey] = Number;
  4067. schema.add(o);
  4068. }
  4069. let model;
  4070. if (typeof name === 'function' && name.prototype instanceof Model) {
  4071. model = name;
  4072. name = model.name;
  4073. schema.loadClass(model, false);
  4074. model.prototype.$isMongooseModelPrototype = true;
  4075. } else {
  4076. // generate new class
  4077. model = function model(doc, fields, skipId) {
  4078. model.hooks.execPreSync('createModel', doc);
  4079. if (!(this instanceof model)) {
  4080. return new model(doc, fields, skipId);
  4081. }
  4082. const discriminatorKey = model.schema.options.discriminatorKey;
  4083. // If discriminator key is set, use the discriminator instead (gh-7586)
  4084. if (model.discriminators != null &&
  4085. doc != null &&
  4086. doc[discriminatorKey] != null &&
  4087. model.discriminators[doc[discriminatorKey]] != null) {
  4088. return new model.discriminators[doc[discriminatorKey]](doc, fields, skipId);
  4089. }
  4090. // Otherwise, just use the top-level model
  4091. Model.call(this, doc, fields, skipId);
  4092. };
  4093. }
  4094. model.hooks = schema.s.hooks.clone();
  4095. model.base = base;
  4096. model.modelName = name;
  4097. if (!(model.prototype instanceof Model)) {
  4098. model.__proto__ = Model;
  4099. model.prototype.__proto__ = Model.prototype;
  4100. }
  4101. model.model = Model.prototype.model;
  4102. model.db = model.prototype.db = connection;
  4103. model.discriminators = model.prototype.discriminators = undefined;
  4104. model[modelSymbol] = true;
  4105. model.events = new EventEmitter();
  4106. model.prototype.$__setSchema(schema);
  4107. const _userProvidedOptions = schema._userProvidedOptions || {};
  4108. // `bufferCommands` is true by default...
  4109. let bufferCommands = true;
  4110. // First, take the global option
  4111. if (connection.base.get('bufferCommands') != null) {
  4112. bufferCommands = connection.base.get('bufferCommands');
  4113. }
  4114. // Connection-specific overrides the global option
  4115. if (connection.config.bufferCommands != null) {
  4116. bufferCommands = connection.config.bufferCommands;
  4117. }
  4118. // And schema options override global and connection
  4119. if (_userProvidedOptions.bufferCommands != null) {
  4120. bufferCommands = _userProvidedOptions.bufferCommands;
  4121. }
  4122. const collectionOptions = {
  4123. bufferCommands: bufferCommands,
  4124. capped: schema.options.capped,
  4125. Promise: model.base.Promise
  4126. };
  4127. model.prototype.collection = connection.collection(
  4128. collectionName,
  4129. collectionOptions
  4130. );
  4131. model.prototype[modelCollectionSymbol] = model.prototype.collection;
  4132. // apply methods and statics
  4133. applyMethods(model, schema);
  4134. applyStatics(model, schema);
  4135. applyHooks(model, schema);
  4136. applyStaticHooks(model, schema.s.hooks, schema.statics);
  4137. model.schema = model.prototype.schema;
  4138. model.collection = model.prototype.collection;
  4139. // Create custom query constructor
  4140. model.Query = function() {
  4141. Query.apply(this, arguments);
  4142. };
  4143. model.Query.prototype = Object.create(Query.prototype);
  4144. model.Query.base = Query.base;
  4145. applyQueryMiddleware(model.Query, model);
  4146. applyQueryMethods(model, schema.query);
  4147. return model;
  4148. };
  4149. /*!
  4150. * Register custom query methods for this model
  4151. *
  4152. * @param {Model} model
  4153. * @param {Schema} schema
  4154. */
  4155. function applyQueryMethods(model, methods) {
  4156. for (const i in methods) {
  4157. model.Query.prototype[i] = methods[i];
  4158. }
  4159. }
  4160. /*!
  4161. * Subclass this model with `conn`, `schema`, and `collection` settings.
  4162. *
  4163. * @param {Connection} conn
  4164. * @param {Schema} [schema]
  4165. * @param {String} [collection]
  4166. * @return {Model}
  4167. */
  4168. Model.__subclass = function subclass(conn, schema, collection) {
  4169. // subclass model using this connection and collection name
  4170. const _this = this;
  4171. const Model = function Model(doc, fields, skipId) {
  4172. if (!(this instanceof Model)) {
  4173. return new Model(doc, fields, skipId);
  4174. }
  4175. _this.call(this, doc, fields, skipId);
  4176. };
  4177. Model.__proto__ = _this;
  4178. Model.prototype.__proto__ = _this.prototype;
  4179. Model.db = Model.prototype.db = conn;
  4180. _this[subclassedSymbol] = _this[subclassedSymbol] || [];
  4181. _this[subclassedSymbol].push(Model);
  4182. if (_this.discriminators != null) {
  4183. Model.discriminators = {};
  4184. for (const key of Object.keys(_this.discriminators)) {
  4185. Model.discriminators[key] = _this.discriminators[key].
  4186. __subclass(_this.db, _this.discriminators[key].schema, collection);
  4187. }
  4188. }
  4189. const s = schema && typeof schema !== 'string'
  4190. ? schema
  4191. : _this.prototype.schema;
  4192. const options = s.options || {};
  4193. const _userProvidedOptions = s._userProvidedOptions || {};
  4194. if (!collection) {
  4195. collection = _this.prototype.schema.get('collection') ||
  4196. utils.toCollectionName(_this.modelName, this.base.pluralize());
  4197. }
  4198. let bufferCommands = true;
  4199. if (s) {
  4200. if (conn.config.bufferCommands != null) {
  4201. bufferCommands = conn.config.bufferCommands;
  4202. }
  4203. if (_userProvidedOptions.bufferCommands != null) {
  4204. bufferCommands = _userProvidedOptions.bufferCommands;
  4205. }
  4206. }
  4207. const collectionOptions = {
  4208. bufferCommands: bufferCommands,
  4209. capped: s && options.capped
  4210. };
  4211. Model.prototype.collection = conn.collection(collection, collectionOptions);
  4212. Model.prototype[modelCollectionSymbol] = Model.prototype.collection;
  4213. Model.collection = Model.prototype.collection;
  4214. // Errors handled internally, so ignore
  4215. Model.init(() => {});
  4216. return Model;
  4217. };
  4218. Model.$wrapCallback = function(callback) {
  4219. if (callback == null) {
  4220. return callback;
  4221. }
  4222. if (typeof callback !== 'function') {
  4223. throw new Error('Callback must be a function, got ' + callback);
  4224. }
  4225. const _this = this;
  4226. return function() {
  4227. try {
  4228. callback.apply(null, arguments);
  4229. } catch (error) {
  4230. _this.emit('error', error);
  4231. }
  4232. };
  4233. };
  4234. /*!
  4235. * Module exports.
  4236. */
  4237. module.exports = exports = Model;