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

model.js 145KB

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