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

model.js 144KB

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