model.js 146 KB

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