model.js 169 KB

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