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

model.js 163KB

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