document.js 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const EventEmitter = require('events').EventEmitter;
  6. const InternalCache = require('./internal');
  7. const MongooseError = require('./error/index');
  8. const MixedSchema = require('./schema/mixed');
  9. const ObjectExpectedError = require('./error/objectExpected');
  10. const ObjectParameterError = require('./error/objectParameter');
  11. const ParallelValidateError = require('./error/parallelValidate');
  12. const Schema = require('./schema');
  13. const StrictModeError = require('./error/strict');
  14. const ValidationError = require('./error/validation');
  15. const ValidatorError = require('./error/validator');
  16. const VirtualType = require('./virtualtype');
  17. const promiseOrCallback = require('./helpers/promiseOrCallback');
  18. const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');
  19. const compile = require('./helpers/document/compile').compile;
  20. const defineKey = require('./helpers/document/compile').defineKey;
  21. const flatten = require('./helpers/common').flatten;
  22. const get = require('./helpers/get');
  23. const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
  24. const handleSpreadDoc = require('./helpers/document/handleSpreadDoc');
  25. const idGetter = require('./plugins/idGetter');
  26. const immediate = require('./helpers/immediate');
  27. const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
  28. const isExclusive = require('./helpers/projection/isExclusive');
  29. const inspect = require('util').inspect;
  30. const internalToObjectOptions = require('./options').internalToObjectOptions;
  31. const mpath = require('mpath');
  32. const queryhelpers = require('./queryhelpers');
  33. const utils = require('./utils');
  34. const isPromise = require('./helpers/isPromise');
  35. const clone = utils.clone;
  36. const deepEqual = utils.deepEqual;
  37. const isMongooseObject = utils.isMongooseObject;
  38. const arrayAtomicsBackupSymbol = Symbol('mongoose.Array#atomicsBackup');
  39. const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
  40. const documentArrayParent = require('./helpers/symbols').documentArrayParent;
  41. const documentIsModified = require('./helpers/symbols').documentIsModified;
  42. const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths;
  43. const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;
  44. const getSymbol = require('./helpers/symbols').getSymbol;
  45. const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;
  46. const scopeSymbol = require('./helpers/symbols').scopeSymbol;
  47. const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;
  48. let DocumentArray;
  49. let MongooseArray;
  50. let Embedded;
  51. const specialProperties = utils.specialProperties;
  52. /**
  53. * The core Mongoose document constructor. You should not call this directly,
  54. * the Mongoose [Model constructor](./api.html#Model) calls this for you.
  55. *
  56. * @param {Object} obj the values to set
  57. * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
  58. * @param {Object} [options] various configuration options for the document
  59. * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document.
  60. * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
  61. * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose.
  62. * @event `save`: Emitted when the document is successfully saved
  63. * @api private
  64. */
  65. function Document(obj, fields, skipId, options) {
  66. if (typeof skipId === 'object' && skipId != null) {
  67. options = skipId;
  68. skipId = options.skipId;
  69. }
  70. options = Object.assign({}, options);
  71. const defaults = get(options, 'defaults', true);
  72. options.defaults = defaults;
  73. // Support `browserDocument.js` syntax
  74. if (this.$__schema == null) {
  75. const _schema = utils.isObject(fields) && !fields.instanceOfSchema ?
  76. new Schema(fields) :
  77. fields;
  78. this.$__setSchema(_schema);
  79. fields = skipId;
  80. skipId = options;
  81. options = arguments[4] || {};
  82. }
  83. this.$__ = new InternalCache;
  84. this.$__.emitter = new EventEmitter();
  85. this.isNew = 'isNew' in options ? options.isNew : true;
  86. this.errors = undefined;
  87. this.$__.$options = options || {};
  88. this.$locals = {};
  89. this.$op = null;
  90. if (obj != null && typeof obj !== 'object') {
  91. throw new ObjectParameterError(obj, 'obj', 'Document');
  92. }
  93. const schema = this.$__schema;
  94. if (typeof fields === 'boolean' || fields === 'throw') {
  95. this.$__.strictMode = fields;
  96. fields = undefined;
  97. } else {
  98. this.$__.strictMode = schema.options.strict;
  99. this.$__.selected = fields;
  100. }
  101. const requiredPaths = schema.requiredPaths(true);
  102. for (const path of requiredPaths) {
  103. this.$__.activePaths.require(path);
  104. }
  105. this.$__.emitter.setMaxListeners(0);
  106. let exclude = null;
  107. // determine if this doc is a result of a query with
  108. // excluded fields
  109. if (utils.isPOJO(fields)) {
  110. exclude = isExclusive(fields);
  111. }
  112. const hasIncludedChildren = exclude === false && fields ?
  113. $__hasIncludedChildren(fields) :
  114. {};
  115. if (this._doc == null) {
  116. this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false);
  117. // By default, defaults get applied **before** setting initial values
  118. // Re: gh-6155
  119. if (defaults) {
  120. $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, {
  121. isNew: this.isNew
  122. });
  123. }
  124. }
  125. if (obj) {
  126. // Skip set hooks
  127. if (this.$__original_set) {
  128. this.$__original_set(obj, undefined, true);
  129. } else {
  130. this.$set(obj, undefined, true);
  131. }
  132. if (obj instanceof Document) {
  133. this.isNew = obj.isNew;
  134. }
  135. }
  136. // Function defaults get applied **after** setting initial values so they
  137. // see the full doc rather than an empty one, unless they opt out.
  138. // Re: gh-3781, gh-6155
  139. if (options.willInit && defaults) {
  140. EventEmitter.prototype.once.call(this, 'init', () => {
  141. $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
  142. isNew: this.isNew
  143. });
  144. });
  145. } else if (defaults) {
  146. $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, {
  147. isNew: this.isNew
  148. });
  149. }
  150. this.$__._id = this._id;
  151. if (!this.$__.strictMode && obj) {
  152. const _this = this;
  153. const keys = Object.keys(this._doc);
  154. keys.forEach(function(key) {
  155. if (!(key in schema.tree)) {
  156. defineKey(key, null, _this);
  157. }
  158. });
  159. }
  160. applyQueue(this);
  161. }
  162. /*!
  163. * Document exposes the NodeJS event emitter API, so you can use
  164. * `on`, `once`, etc.
  165. */
  166. utils.each(
  167. ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
  168. 'removeAllListeners', 'addListener'],
  169. function(emitterFn) {
  170. Document.prototype[emitterFn] = function() {
  171. return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments);
  172. };
  173. });
  174. Document.prototype.constructor = Document;
  175. for (const i in EventEmitter.prototype) {
  176. Document[i] = EventEmitter.prototype[i];
  177. }
  178. /**
  179. * The document's internal schema.
  180. *
  181. * @api private
  182. * @property schema
  183. * @memberOf Document
  184. * @instance
  185. */
  186. Document.prototype.$__schema;
  187. /**
  188. * The document's schema.
  189. *
  190. * @api public
  191. * @property schema
  192. * @memberOf Document
  193. * @instance
  194. */
  195. Document.prototype.schema;
  196. /**
  197. * Empty object that you can use for storing properties on the document. This
  198. * is handy for passing data to middleware without conflicting with Mongoose
  199. * internals.
  200. *
  201. * ####Example:
  202. *
  203. * schema.pre('save', function() {
  204. * // Mongoose will set `isNew` to `false` if `save()` succeeds
  205. * this.$locals.wasNew = this.isNew;
  206. * });
  207. *
  208. * schema.post('save', function() {
  209. * // Prints true if `isNew` was set before `save()`
  210. * console.log(this.$locals.wasNew);
  211. * });
  212. *
  213. * @api public
  214. * @property $locals
  215. * @memberOf Document
  216. * @instance
  217. */
  218. Object.defineProperty(Document.prototype, '$locals', {
  219. configurable: false,
  220. enumerable: false,
  221. writable: true
  222. });
  223. /**
  224. * Boolean flag specifying if the document is new.
  225. *
  226. * @api public
  227. * @property isNew
  228. * @memberOf Document
  229. * @instance
  230. */
  231. Document.prototype.isNew;
  232. /**
  233. * The string version of this documents _id.
  234. *
  235. * ####Note:
  236. *
  237. * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time.
  238. *
  239. * new Schema({ name: String }, { id: false });
  240. *
  241. * @api public
  242. * @see Schema options /docs/guide.html#options
  243. * @property id
  244. * @memberOf Document
  245. * @instance
  246. */
  247. Document.prototype.id;
  248. /**
  249. * Hash containing current validation errors.
  250. *
  251. * @api public
  252. * @property errors
  253. * @memberOf Document
  254. * @instance
  255. */
  256. Document.prototype.errors;
  257. /**
  258. * A string containing the current operation that Mongoose is executing
  259. * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`.
  260. *
  261. * ####Example:
  262. *
  263. * const doc = new Model({ name: 'test' });
  264. * doc.$op; // null
  265. *
  266. * const promise = doc.save();
  267. * doc.$op; // 'save'
  268. *
  269. * await promise;
  270. * doc.$op; // null
  271. *
  272. * @api public
  273. * @property $op
  274. * @memberOf Document
  275. * @instance
  276. */
  277. Document.prototype.$op;
  278. /*!
  279. * ignore
  280. */
  281. function $__hasIncludedChildren(fields) {
  282. const hasIncludedChildren = {};
  283. const keys = Object.keys(fields);
  284. for (const key of keys) {
  285. const parts = key.split('.');
  286. const c = [];
  287. for (const part of parts) {
  288. c.push(part);
  289. hasIncludedChildren[c.join('.')] = 1;
  290. }
  291. }
  292. return hasIncludedChildren;
  293. }
  294. /*!
  295. * ignore
  296. */
  297. function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) {
  298. const paths = Object.keys(doc.$__schema.paths);
  299. const plen = paths.length;
  300. for (let i = 0; i < plen; ++i) {
  301. let def;
  302. let curPath = '';
  303. const p = paths[i];
  304. if (p === '_id' && skipId) {
  305. continue;
  306. }
  307. const type = doc.$__schema.paths[p];
  308. const path = type.splitPath();
  309. const len = path.length;
  310. let included = false;
  311. let doc_ = doc._doc;
  312. for (let j = 0; j < len; ++j) {
  313. if (doc_ == null) {
  314. break;
  315. }
  316. const piece = path[j];
  317. curPath += (!curPath.length ? '' : '.') + piece;
  318. if (exclude === true) {
  319. if (curPath in fields) {
  320. break;
  321. }
  322. } else if (exclude === false && fields && !included) {
  323. if (curPath in fields) {
  324. included = true;
  325. } else if (!hasIncludedChildren[curPath]) {
  326. break;
  327. }
  328. }
  329. if (j === len - 1) {
  330. if (doc_[piece] !== void 0) {
  331. break;
  332. }
  333. if (typeof type.defaultValue === 'function') {
  334. if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) {
  335. break;
  336. }
  337. if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) {
  338. break;
  339. }
  340. } else if (!isBeforeSetters) {
  341. // Non-function defaults should always run **before** setters
  342. continue;
  343. }
  344. if (pathsToSkip && pathsToSkip[curPath]) {
  345. break;
  346. }
  347. if (fields && exclude !== null) {
  348. if (exclude === true) {
  349. // apply defaults to all non-excluded fields
  350. if (p in fields) {
  351. continue;
  352. }
  353. try {
  354. def = type.getDefault(doc, false);
  355. } catch (err) {
  356. doc.invalidate(p, err);
  357. break;
  358. }
  359. if (typeof def !== 'undefined') {
  360. doc_[piece] = def;
  361. doc.$__.activePaths.default(p);
  362. }
  363. } else if (included) {
  364. // selected field
  365. try {
  366. def = type.getDefault(doc, false);
  367. } catch (err) {
  368. doc.invalidate(p, err);
  369. break;
  370. }
  371. if (typeof def !== 'undefined') {
  372. doc_[piece] = def;
  373. doc.$__.activePaths.default(p);
  374. }
  375. }
  376. } else {
  377. try {
  378. def = type.getDefault(doc, false);
  379. } catch (err) {
  380. doc.invalidate(p, err);
  381. break;
  382. }
  383. if (typeof def !== 'undefined') {
  384. doc_[piece] = def;
  385. doc.$__.activePaths.default(p);
  386. }
  387. }
  388. } else {
  389. doc_ = doc_[piece];
  390. }
  391. }
  392. }
  393. }
  394. /**
  395. * Builds the default doc structure
  396. *
  397. * @param {Object} obj
  398. * @param {Object} [fields]
  399. * @param {Boolean} [skipId]
  400. * @api private
  401. * @method $__buildDoc
  402. * @memberOf Document
  403. * @instance
  404. */
  405. Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) {
  406. const doc = {};
  407. const paths = Object.keys(this.$__schema.paths).
  408. // Don't build up any paths that are underneath a map, we don't know
  409. // what the keys will be
  410. filter(p => !p.includes('$*'));
  411. const plen = paths.length;
  412. let ii = 0;
  413. for (; ii < plen; ++ii) {
  414. const p = paths[ii];
  415. if (p === '_id') {
  416. if (skipId) {
  417. continue;
  418. }
  419. if (obj && '_id' in obj) {
  420. continue;
  421. }
  422. }
  423. const path = this.$__schema.paths[p].splitPath();
  424. const len = path.length;
  425. const last = len - 1;
  426. let curPath = '';
  427. let doc_ = doc;
  428. let included = false;
  429. for (let i = 0; i < len; ++i) {
  430. const piece = path[i];
  431. curPath += (!curPath.length ? '' : '.') + piece;
  432. // support excluding intermediary levels
  433. if (exclude === true) {
  434. if (curPath in fields) {
  435. break;
  436. }
  437. } else if (exclude === false && fields && !included) {
  438. if (curPath in fields) {
  439. included = true;
  440. } else if (!hasIncludedChildren[curPath]) {
  441. break;
  442. }
  443. }
  444. if (i < last) {
  445. doc_ = doc_[piece] || (doc_[piece] = {});
  446. }
  447. }
  448. }
  449. this._doc = doc;
  450. };
  451. /*!
  452. * Converts to POJO when you use the document for querying
  453. */
  454. Document.prototype.toBSON = function() {
  455. return this.toObject(internalToObjectOptions);
  456. };
  457. /**
  458. * Initializes the document without setters or marking anything modified.
  459. *
  460. * Called internally after a document is returned from mongodb. Normally,
  461. * you do **not** need to call this function on your own.
  462. *
  463. * This function triggers `init` [middleware](/docs/middleware.html).
  464. * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous).
  465. *
  466. * @param {Object} doc document returned by mongo
  467. * @api public
  468. * @memberOf Document
  469. * @instance
  470. */
  471. Document.prototype.init = function(doc, opts, fn) {
  472. if (typeof opts === 'function') {
  473. fn = opts;
  474. opts = null;
  475. }
  476. this.$__init(doc, opts);
  477. if (fn) {
  478. fn(null, this);
  479. }
  480. return this;
  481. };
  482. /*!
  483. * ignore
  484. */
  485. Document.prototype.$__init = function(doc, opts) {
  486. this.isNew = false;
  487. this.$init = true;
  488. opts = opts || {};
  489. // handle docs with populated paths
  490. // If doc._id is not null or undefined
  491. if (doc._id != null && opts.populated && opts.populated.length) {
  492. const id = String(doc._id);
  493. for (const item of opts.populated) {
  494. if (item.isVirtual) {
  495. this.populated(item.path, utils.getValue(item.path, doc), item);
  496. } else {
  497. this.populated(item.path, item._docs[id], item);
  498. }
  499. if (item._childDocs == null) {
  500. continue;
  501. }
  502. for (const child of item._childDocs) {
  503. if (child == null || child.$__ == null) {
  504. continue;
  505. }
  506. child.$__.parent = this;
  507. }
  508. item._childDocs = [];
  509. }
  510. }
  511. init(this, doc, this._doc, opts);
  512. markArraySubdocsPopulated(this, opts.populated);
  513. this.emit('init', this);
  514. this.constructor.emit('init', this);
  515. this.$__._id = this._id;
  516. return this;
  517. };
  518. /*!
  519. * If populating a path within a document array, make sure each
  520. * subdoc within the array knows its subpaths are populated.
  521. *
  522. * ####Example:
  523. * const doc = await Article.findOne().populate('comments.author');
  524. * doc.comments[0].populated('author'); // Should be set
  525. */
  526. function markArraySubdocsPopulated(doc, populated) {
  527. if (doc._id == null || populated == null || populated.length === 0) {
  528. return;
  529. }
  530. const id = String(doc._id);
  531. for (const item of populated) {
  532. if (item.isVirtual) {
  533. continue;
  534. }
  535. const path = item.path;
  536. const pieces = path.split('.');
  537. for (let i = 0; i < pieces.length - 1; ++i) {
  538. const subpath = pieces.slice(0, i + 1).join('.');
  539. const rest = pieces.slice(i + 1).join('.');
  540. const val = doc.get(subpath);
  541. if (val == null) {
  542. continue;
  543. }
  544. if (val.isMongooseDocumentArray) {
  545. for (let j = 0; j < val.length; ++j) {
  546. val[j].populated(rest, item._docs[id] == null ? [] : item._docs[id][j], item);
  547. }
  548. break;
  549. }
  550. }
  551. }
  552. }
  553. /*!
  554. * Init helper.
  555. *
  556. * @param {Object} self document instance
  557. * @param {Object} obj raw mongodb doc
  558. * @param {Object} doc object we are initializing
  559. * @api private
  560. */
  561. function init(self, obj, doc, opts, prefix) {
  562. prefix = prefix || '';
  563. const keys = Object.keys(obj);
  564. const len = keys.length;
  565. let schema;
  566. let path;
  567. let i;
  568. let index = 0;
  569. while (index < len) {
  570. _init(index++);
  571. }
  572. function _init(index) {
  573. i = keys[index];
  574. path = prefix + i;
  575. schema = self.$__schema.path(path);
  576. // Should still work if not a model-level discriminator, but should not be
  577. // necessary. This is *only* to catch the case where we queried using the
  578. // base model and the discriminated model has a projection
  579. if (self.$__schema.$isRootDiscriminator && !self.$__isSelected(path)) {
  580. return;
  581. }
  582. if (!schema && utils.isPOJO(obj[i])) {
  583. // assume nested object
  584. if (!doc[i]) {
  585. doc[i] = {};
  586. }
  587. init(self, obj[i], doc[i], opts, path + '.');
  588. } else if (!schema) {
  589. doc[i] = obj[i];
  590. } else {
  591. if (obj[i] === null) {
  592. doc[i] = schema._castNullish(null);
  593. } else if (obj[i] !== undefined) {
  594. const intCache = obj[i].$__ || {};
  595. const wasPopulated = intCache.wasPopulated || null;
  596. if (schema && !wasPopulated) {
  597. try {
  598. doc[i] = schema.cast(obj[i], self, true);
  599. } catch (e) {
  600. self.invalidate(e.path, new ValidatorError({
  601. path: e.path,
  602. message: e.message,
  603. type: 'cast',
  604. value: e.value,
  605. reason: e
  606. }));
  607. }
  608. } else {
  609. doc[i] = obj[i];
  610. }
  611. }
  612. // mark as hydrated
  613. if (!self.isModified(path)) {
  614. self.$__.activePaths.init(path);
  615. }
  616. }
  617. }
  618. }
  619. /**
  620. * Sends an update command with this document `_id` as the query selector.
  621. *
  622. * ####Example:
  623. *
  624. * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
  625. *
  626. * ####Valid options:
  627. *
  628. * - same as in [Model.update](#model_Model.update)
  629. *
  630. * @see Model.update #model_Model.update
  631. * @param {Object} doc
  632. * @param {Object} options
  633. * @param {Function} callback
  634. * @return {Query}
  635. * @api public
  636. * @memberOf Document
  637. * @instance
  638. */
  639. Document.prototype.update = function update() {
  640. const args = utils.args(arguments);
  641. args.unshift({ _id: this._id });
  642. const query = this.constructor.update.apply(this.constructor, args);
  643. if (this.$session() != null) {
  644. if (!('session' in query.options)) {
  645. query.options.session = this.$session();
  646. }
  647. }
  648. return query;
  649. };
  650. /**
  651. * Sends an updateOne command with this document `_id` as the query selector.
  652. *
  653. * ####Example:
  654. *
  655. * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);
  656. *
  657. * ####Valid options:
  658. *
  659. * - same as in [Model.updateOne](#model_Model.updateOne)
  660. *
  661. * @see Model.updateOne #model_Model.updateOne
  662. * @param {Object} doc
  663. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  664. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html).
  665. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  666. * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
  667. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
  668. * @param {Function} callback
  669. * @return {Query}
  670. * @api public
  671. * @memberOf Document
  672. * @instance
  673. */
  674. Document.prototype.updateOne = function updateOne(doc, options, callback) {
  675. const query = this.constructor.updateOne({ _id: this._id }, doc, options);
  676. query.pre(cb => {
  677. this.constructor._middleware.execPre('updateOne', this, [this], cb);
  678. });
  679. query.post(cb => {
  680. this.constructor._middleware.execPost('updateOne', this, [this], {}, cb);
  681. });
  682. if (this.$session() != null) {
  683. if (!('session' in query.options)) {
  684. query.options.session = this.$session();
  685. }
  686. }
  687. if (callback != null) {
  688. return query.exec(callback);
  689. }
  690. return query;
  691. };
  692. /**
  693. * Sends a replaceOne command with this document `_id` as the query selector.
  694. *
  695. * ####Valid options:
  696. *
  697. * - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne)
  698. *
  699. * @see Model.replaceOne #model_Model.replaceOne
  700. * @param {Object} doc
  701. * @param {Object} options
  702. * @param {Function} callback
  703. * @return {Query}
  704. * @api public
  705. * @memberOf Document
  706. * @instance
  707. */
  708. Document.prototype.replaceOne = function replaceOne() {
  709. const args = utils.args(arguments);
  710. args.unshift({ _id: this._id });
  711. return this.constructor.replaceOne.apply(this.constructor, args);
  712. };
  713. /**
  714. * Getter/setter around the session associated with this document. Used to
  715. * automatically set `session` if you `save()` a doc that you got from a
  716. * query with an associated session.
  717. *
  718. * ####Example:
  719. *
  720. * const session = MyModel.startSession();
  721. * const doc = await MyModel.findOne().session(session);
  722. * doc.$session() === session; // true
  723. * doc.$session(null);
  724. * doc.$session() === null; // true
  725. *
  726. * If this is a top-level document, setting the session propagates to all child
  727. * docs.
  728. *
  729. * @param {ClientSession} [session] overwrite the current session
  730. * @return {ClientSession}
  731. * @method $session
  732. * @api public
  733. * @memberOf Document
  734. */
  735. Document.prototype.$session = function $session(session) {
  736. if (arguments.length === 0) {
  737. return this.$__.session;
  738. }
  739. this.$__.session = session;
  740. if (!this.ownerDocument) {
  741. const subdocs = this.$getAllSubdocs();
  742. for (const child of subdocs) {
  743. child.$session(session);
  744. }
  745. }
  746. return session;
  747. };
  748. /**
  749. * Overwrite all values in this document with the values of `obj`, except
  750. * for immutable properties. Behaves similarly to `set()`, except for it
  751. * unsets all properties that aren't in `obj`.
  752. *
  753. * @param {Object} obj the object to overwrite this document with
  754. * @method overwrite
  755. * @name overwrite
  756. * @memberOf Document
  757. * @instance
  758. * @api public
  759. */
  760. Document.prototype.overwrite = function overwrite(obj) {
  761. const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj))));
  762. for (const key of keys) {
  763. if (key === '_id') {
  764. continue;
  765. }
  766. // Explicitly skip version key
  767. if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) {
  768. continue;
  769. }
  770. if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) {
  771. continue;
  772. }
  773. this.$set(key, obj[key]);
  774. }
  775. return this;
  776. };
  777. /**
  778. * Alias for `set()`, used internally to avoid conflicts
  779. *
  780. * @param {String|Object} path path or object of key/vals to set
  781. * @param {Any} val the value to set
  782. * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
  783. * @param {Object} [options] optionally specify options that modify the behavior of the set
  784. * @method $set
  785. * @name $set
  786. * @memberOf Document
  787. * @instance
  788. * @api public
  789. */
  790. Document.prototype.$set = function $set(path, val, type, options) {
  791. if (utils.isPOJO(type)) {
  792. options = type;
  793. type = undefined;
  794. }
  795. options = options || {};
  796. const merge = options.merge;
  797. const adhoc = type && type !== true;
  798. const constructing = type === true;
  799. let adhocs;
  800. let keys;
  801. let i = 0;
  802. let pathtype;
  803. let key;
  804. let prefix;
  805. const strict = 'strict' in options
  806. ? options.strict
  807. : this.$__.strictMode;
  808. if (adhoc) {
  809. adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
  810. adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options);
  811. }
  812. if (path == null) {
  813. const _ = path;
  814. path = val;
  815. val = _;
  816. } else if (typeof path !== 'string') {
  817. // new Document({ key: val })
  818. if (path instanceof Document) {
  819. if (path.$__isNested) {
  820. path = path.toObject();
  821. } else {
  822. path = path._doc;
  823. }
  824. }
  825. if (path == null) {
  826. const _ = path;
  827. path = val;
  828. val = _;
  829. }
  830. prefix = val ? val + '.' : '';
  831. keys = Object.keys(path);
  832. const len = keys.length;
  833. // `_skipMinimizeTopLevel` is because we may have deleted the top-level
  834. // nested key to ensure key order.
  835. const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false);
  836. if (len === 0 && _skipMinimizeTopLevel) {
  837. delete options._skipMinimizeTopLevel;
  838. if (val) {
  839. this.$set(val, {});
  840. }
  841. return this;
  842. }
  843. for (let i = 0; i < len; ++i) {
  844. key = keys[i];
  845. const pathName = prefix + key;
  846. pathtype = this.$__schema.pathType(pathName);
  847. // On initial set, delete any nested keys if we're going to overwrite
  848. // them to ensure we keep the user's key order.
  849. if (type === true &&
  850. !prefix &&
  851. path[key] != null &&
  852. pathtype === 'nested' &&
  853. this._doc[key] != null &&
  854. Object.keys(this._doc[key]).length === 0) {
  855. delete this._doc[key];
  856. // Make sure we set `{}` back even if we minimize re: gh-8565
  857. options = Object.assign({}, options, { _skipMinimizeTopLevel: true });
  858. }
  859. const someCondition = typeof path[key] === 'object' &&
  860. !utils.isNativeObject(path[key]) &&
  861. !utils.isMongooseType(path[key]) &&
  862. path[key] != null &&
  863. pathtype !== 'virtual' &&
  864. pathtype !== 'real' &&
  865. pathtype !== 'adhocOrUndefined' &&
  866. !(this.$__path(pathName) instanceof MixedSchema) &&
  867. !(this.$__schema.paths[pathName] &&
  868. this.$__schema.paths[pathName].options &&
  869. this.$__schema.paths[pathName].options.ref);
  870. if (someCondition) {
  871. this.$__.$setCalled.add(prefix + key);
  872. this.$set(path[key], prefix + key, constructing, options);
  873. } else if (strict) {
  874. // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039)
  875. if (constructing && path[key] === void 0 &&
  876. this.get(pathName) !== void 0) {
  877. continue;
  878. }
  879. if (pathtype === 'adhocOrUndefined') {
  880. pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true });
  881. }
  882. if (pathtype === 'real' || pathtype === 'virtual') {
  883. // Check for setting single embedded schema to document (gh-3535)
  884. let p = path[key];
  885. if (this.$__schema.paths[pathName] &&
  886. this.$__schema.paths[pathName].$isSingleNested &&
  887. path[key] instanceof Document) {
  888. p = p.toObject({ virtuals: false, transform: false });
  889. }
  890. this.$set(prefix + key, p, constructing, options);
  891. } else if (pathtype === 'nested' && path[key] instanceof Document) {
  892. this.$set(prefix + key,
  893. path[key].toObject({ transform: false }), constructing, options);
  894. } else if (strict === 'throw') {
  895. if (pathtype === 'nested') {
  896. throw new ObjectExpectedError(key, path[key]);
  897. } else {
  898. throw new StrictModeError(key);
  899. }
  900. }
  901. } else if (path[key] !== void 0) {
  902. this.$set(prefix + key, path[key], constructing, options);
  903. }
  904. }
  905. return this;
  906. } else {
  907. this.$__.$setCalled.add(path);
  908. }
  909. let pathType = this.$__schema.pathType(path);
  910. if (pathType === 'adhocOrUndefined') {
  911. pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true });
  912. }
  913. // Assume this is a Mongoose document that was copied into a POJO using
  914. // `Object.assign()` or `{...doc}`
  915. val = handleSpreadDoc(val);
  916. if (pathType === 'nested' && val) {
  917. if (typeof val === 'object' && val != null) {
  918. const hasPriorVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path);
  919. if (this.$__.savedState != null && !this.isNew && !this.$__.savedState.hasOwnProperty(path)) {
  920. const priorVal = this.$__getValue(path);
  921. this.$__.savedState[path] = priorVal;
  922. const keys = Object.keys(priorVal || {});
  923. for (const key of keys) {
  924. this.$__.savedState[path + '.' + key] = priorVal[key];
  925. }
  926. }
  927. if (!merge) {
  928. this.$__setValue(path, null);
  929. cleanModifiedSubpaths(this, path);
  930. } else {
  931. return this.$set(val, path, constructing);
  932. }
  933. const keys = Object.keys(val);
  934. this.$__setValue(path, {});
  935. for (const key of keys) {
  936. this.$set(path + '.' + key, val[key], constructing);
  937. }
  938. if (hasPriorVal && utils.deepEqual(this.$__.savedState[path], val)) {
  939. this.unmarkModified(path);
  940. } else {
  941. this.markModified(path);
  942. }
  943. cleanModifiedSubpaths(this, path, { skipDocArrays: true });
  944. return this;
  945. }
  946. this.invalidate(path, new MongooseError.CastError('Object', val, path));
  947. return this;
  948. }
  949. let schema;
  950. const parts = path.indexOf('.') === -1 ? [path] : path.split('.');
  951. // Might need to change path for top-level alias
  952. if (typeof this.$__schema.aliases[parts[0]] == 'string') {
  953. parts[0] = this.$__schema.aliases[parts[0]];
  954. }
  955. if (pathType === 'adhocOrUndefined' && strict) {
  956. // check for roots that are Mixed types
  957. let mixed;
  958. for (i = 0; i < parts.length; ++i) {
  959. const subpath = parts.slice(0, i + 1).join('.');
  960. // If path is underneath a virtual, bypass everything and just set it.
  961. if (i + 1 < parts.length && this.$__schema.pathType(subpath) === 'virtual') {
  962. mpath.set(path, val, this);
  963. return this;
  964. }
  965. schema = this.$__schema.path(subpath);
  966. if (schema == null) {
  967. continue;
  968. }
  969. if (schema instanceof MixedSchema) {
  970. // allow changes to sub paths of mixed types
  971. mixed = true;
  972. break;
  973. }
  974. }
  975. if (schema == null) {
  976. // Check for embedded discriminators
  977. schema = getEmbeddedDiscriminatorPath(this, path);
  978. }
  979. if (!mixed && !schema) {
  980. if (strict === 'throw') {
  981. throw new StrictModeError(path);
  982. }
  983. return this;
  984. }
  985. } else if (pathType === 'virtual') {
  986. schema = this.$__schema.virtualpath(path);
  987. schema.applySetters(val, this);
  988. return this;
  989. } else {
  990. schema = this.$__path(path);
  991. }
  992. // gh-4578, if setting a deeply nested path that doesn't exist yet, create it
  993. let cur = this._doc;
  994. let curPath = '';
  995. for (i = 0; i < parts.length - 1; ++i) {
  996. cur = cur[parts[i]];
  997. curPath += (curPath.length > 0 ? '.' : '') + parts[i];
  998. if (!cur) {
  999. this.$set(curPath, {});
  1000. // Hack re: gh-5800. If nested field is not selected, it probably exists
  1001. // so `MongoError: cannot use the part (nested of nested.num) to
  1002. // traverse the element ({nested: null})` is not likely. If user gets
  1003. // that error, its their fault for now. We should reconsider disallowing
  1004. // modifying not selected paths for 6.x
  1005. if (!this.$__isSelected(curPath)) {
  1006. this.unmarkModified(curPath);
  1007. }
  1008. cur = this.$__getValue(curPath);
  1009. }
  1010. }
  1011. let pathToMark;
  1012. // When using the $set operator the path to the field must already exist.
  1013. // Else mongodb throws: "LEFT_SUBFIELD only supports Object"
  1014. if (parts.length <= 1) {
  1015. pathToMark = path;
  1016. } else {
  1017. for (i = 0; i < parts.length; ++i) {
  1018. const subpath = parts.slice(0, i + 1).join('.');
  1019. if (this.get(subpath, null, { getters: false }) === null) {
  1020. pathToMark = subpath;
  1021. break;
  1022. }
  1023. }
  1024. if (!pathToMark) {
  1025. pathToMark = path;
  1026. }
  1027. }
  1028. // if this doc is being constructed we should not trigger getters
  1029. const priorVal = (() => {
  1030. if (this.$__.$options.priorDoc != null) {
  1031. return this.$__.$options.priorDoc.$__getValue(path);
  1032. }
  1033. if (constructing) {
  1034. return void 0;
  1035. }
  1036. return this.$__getValue(path);
  1037. })();
  1038. if (!schema) {
  1039. this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
  1040. return this;
  1041. }
  1042. // If overwriting a subdocument path, make sure to clear out
  1043. // any errors _before_ setting, so new errors that happen
  1044. // get persisted. Re: #9080
  1045. if (schema.$isSingleNested || schema.$isMongooseArray) {
  1046. _markValidSubpaths(this, path);
  1047. }
  1048. if (schema.$isSingleNested && val != null && merge) {
  1049. if (val instanceof Document) {
  1050. val = val.toObject({ virtuals: false, transform: false });
  1051. }
  1052. const keys = Object.keys(val);
  1053. for (const key of keys) {
  1054. this.$set(path + '.' + key, val[key], constructing, options);
  1055. }
  1056. return this;
  1057. }
  1058. let shouldSet = true;
  1059. try {
  1060. // If the user is trying to set a ref path to a document with
  1061. // the correct model name, treat it as populated
  1062. const refMatches = (() => {
  1063. if (schema.options == null) {
  1064. return false;
  1065. }
  1066. if (!(val instanceof Document)) {
  1067. return false;
  1068. }
  1069. const model = val.constructor;
  1070. // Check ref
  1071. const ref = schema.options.ref;
  1072. if (ref != null && (ref === model.modelName || ref === model.baseModelName)) {
  1073. return true;
  1074. }
  1075. // Check refPath
  1076. const refPath = schema.options.refPath;
  1077. if (refPath == null) {
  1078. return false;
  1079. }
  1080. const modelName = val.get(refPath);
  1081. return modelName === model.modelName || modelName === model.baseModelName;
  1082. })();
  1083. let didPopulate = false;
  1084. if (refMatches && val instanceof Document) {
  1085. this.populated(path, val._id, { [populateModelSymbol]: val.constructor });
  1086. val.$__.wasPopulated = true;
  1087. didPopulate = true;
  1088. }
  1089. let popOpts;
  1090. if (schema.options &&
  1091. Array.isArray(schema.options[this.$__schema.options.typeKey]) &&
  1092. schema.options[this.$__schema.options.typeKey].length &&
  1093. schema.options[this.$__schema.options.typeKey][0].ref &&
  1094. _isManuallyPopulatedArray(val, schema.options[this.$__schema.options.typeKey][0].ref)) {
  1095. if (this.ownerDocument) {
  1096. popOpts = { [populateModelSymbol]: val[0].constructor };
  1097. this.ownerDocument().populated(this.$__fullPath(path),
  1098. val.map(function(v) { return v._id; }), popOpts);
  1099. } else {
  1100. popOpts = { [populateModelSymbol]: val[0].constructor };
  1101. this.populated(path, val.map(function(v) { return v._id; }), popOpts);
  1102. }
  1103. for (const doc of val) {
  1104. doc.$__.wasPopulated = true;
  1105. }
  1106. didPopulate = true;
  1107. }
  1108. if (this.$__schema.singleNestedPaths[path] == null) {
  1109. // If this path is underneath a single nested schema, we'll call the setter
  1110. // later in `$__set()` because we don't take `_doc` when we iterate through
  1111. // a single nested doc. That's to make sure we get the correct context.
  1112. // Otherwise we would double-call the setter, see gh-7196.
  1113. val = schema.applySetters(val, this, false, priorVal);
  1114. }
  1115. if (schema.$isMongooseDocumentArray &&
  1116. Array.isArray(val) &&
  1117. val.length > 0 &&
  1118. val[0] != null &&
  1119. val[0].$__ != null &&
  1120. val[0].$__.populated != null) {
  1121. const populatedPaths = Object.keys(val[0].$__.populated);
  1122. for (const populatedPath of populatedPaths) {
  1123. this.populated(path + '.' + populatedPath,
  1124. val.map(v => v.populated(populatedPath)),
  1125. val[0].$__.populated[populatedPath].options);
  1126. }
  1127. didPopulate = true;
  1128. }
  1129. if (!didPopulate && this.$__.populated) {
  1130. // If this array partially contains populated documents, convert them
  1131. // all to ObjectIds re: #8443
  1132. if (Array.isArray(val) && this.$__.populated[path]) {
  1133. for (let i = 0; i < val.length; ++i) {
  1134. if (val[i] instanceof Document) {
  1135. val[i] = val[i]._id;
  1136. }
  1137. }
  1138. }
  1139. delete this.$__.populated[path];
  1140. }
  1141. if (schema.$isSingleNested && val != null) {
  1142. _checkImmutableSubpaths(val, schema, priorVal);
  1143. }
  1144. this.$markValid(path);
  1145. } catch (e) {
  1146. if (e instanceof MongooseError.StrictModeError && e.isImmutableError) {
  1147. this.invalidate(path, e);
  1148. } else if (e instanceof MongooseError.CastError) {
  1149. this.invalidate(e.path, e);
  1150. if (e.$originalErrorPath) {
  1151. this.invalidate(path,
  1152. new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath));
  1153. }
  1154. } else {
  1155. this.invalidate(path,
  1156. new MongooseError.CastError(schema.instance, val, path, e));
  1157. }
  1158. shouldSet = false;
  1159. }
  1160. if (shouldSet) {
  1161. this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
  1162. if (this.$__.savedState != null) {
  1163. if (!this.isNew && !this.$__.savedState.hasOwnProperty(path)) {
  1164. this.$__.savedState[path] = priorVal;
  1165. } else if (this.$__.savedState.hasOwnProperty(path) && utils.deepEqual(val, this.$__.savedState[path])) {
  1166. this.unmarkModified(path);
  1167. }
  1168. }
  1169. }
  1170. if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) {
  1171. cleanModifiedSubpaths(this, path);
  1172. }
  1173. return this;
  1174. };
  1175. /*!
  1176. * ignore
  1177. */
  1178. function _isManuallyPopulatedArray(val, ref) {
  1179. if (!Array.isArray(val)) {
  1180. return false;
  1181. }
  1182. if (val.length === 0) {
  1183. return false;
  1184. }
  1185. for (const el of val) {
  1186. if (!(el instanceof Document)) {
  1187. return false;
  1188. }
  1189. const modelName = el.constructor.modelName;
  1190. if (modelName == null) {
  1191. return false;
  1192. }
  1193. if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) {
  1194. return false;
  1195. }
  1196. }
  1197. return true;
  1198. }
  1199. /**
  1200. * Sets the value of a path, or many paths.
  1201. *
  1202. * ####Example:
  1203. *
  1204. * // path, value
  1205. * doc.set(path, value)
  1206. *
  1207. * // object
  1208. * doc.set({
  1209. * path : value
  1210. * , path2 : {
  1211. * path : value
  1212. * }
  1213. * })
  1214. *
  1215. * // on-the-fly cast to number
  1216. * doc.set(path, value, Number)
  1217. *
  1218. * // on-the-fly cast to string
  1219. * doc.set(path, value, String)
  1220. *
  1221. * // changing strict mode behavior
  1222. * doc.set(path, value, { strict: false });
  1223. *
  1224. * @param {String|Object} path path or object of key/vals to set
  1225. * @param {Any} val the value to set
  1226. * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
  1227. * @param {Object} [options] optionally specify options that modify the behavior of the set
  1228. * @api public
  1229. * @method set
  1230. * @memberOf Document
  1231. * @instance
  1232. */
  1233. Document.prototype.set = Document.prototype.$set;
  1234. /**
  1235. * Determine if we should mark this change as modified.
  1236. *
  1237. * @return {Boolean}
  1238. * @api private
  1239. * @method $__shouldModify
  1240. * @memberOf Document
  1241. * @instance
  1242. */
  1243. Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
  1244. if (this.isNew) {
  1245. return true;
  1246. }
  1247. // Re: the note about gh-7196, `val` is the raw value without casting or
  1248. // setters if the full path is under a single nested subdoc because we don't
  1249. // want to double run setters. So don't set it as modified. See gh-7264.
  1250. if (this.$__schema.singleNestedPaths[path] != null) {
  1251. return false;
  1252. }
  1253. if (val === void 0 && !this.$__isSelected(path)) {
  1254. // when a path is not selected in a query, its initial
  1255. // value will be undefined.
  1256. return true;
  1257. }
  1258. if (val === void 0 && path in this.$__.activePaths.states.default) {
  1259. // we're just unsetting the default value which was never saved
  1260. return false;
  1261. }
  1262. // gh-3992: if setting a populated field to a doc, don't mark modified
  1263. // if they have the same _id
  1264. if (this.populated(path) &&
  1265. val instanceof Document &&
  1266. deepEqual(val._id, priorVal)) {
  1267. return false;
  1268. }
  1269. if (!deepEqual(val, priorVal || utils.getValue(path, this))) {
  1270. return true;
  1271. }
  1272. if (!constructing &&
  1273. val !== null &&
  1274. val !== undefined &&
  1275. path in this.$__.activePaths.states.default &&
  1276. deepEqual(val, schema.getDefault(this, constructing))) {
  1277. // a path with a default was $unset on the server
  1278. // and the user is setting it to the same value again
  1279. return true;
  1280. }
  1281. return false;
  1282. };
  1283. /**
  1284. * Handles the actual setting of the value and marking the path modified if appropriate.
  1285. *
  1286. * @api private
  1287. * @method $__set
  1288. * @memberOf Document
  1289. * @instance
  1290. */
  1291. Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
  1292. Embedded = Embedded || require('./types/embedded');
  1293. const shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts,
  1294. schema, val, priorVal);
  1295. const _this = this;
  1296. if (shouldModify) {
  1297. this.markModified(pathToMark);
  1298. // handle directly setting arrays (gh-1126)
  1299. MongooseArray || (MongooseArray = require('./types/array'));
  1300. if (val && val.isMongooseArray) {
  1301. val._registerAtomic('$set', val);
  1302. // Update embedded document parent references (gh-5189)
  1303. if (val.isMongooseDocumentArray) {
  1304. val.forEach(function(item) {
  1305. item && item.__parentArray && (item.__parentArray = val);
  1306. });
  1307. }
  1308. // Small hack for gh-1638: if we're overwriting the entire array, ignore
  1309. // paths that were modified before the array overwrite
  1310. this.$__.activePaths.forEach(function(modifiedPath) {
  1311. if (modifiedPath.startsWith(path + '.')) {
  1312. _this.$__.activePaths.ignore(modifiedPath);
  1313. }
  1314. });
  1315. }
  1316. }
  1317. let obj = this._doc;
  1318. let i = 0;
  1319. const l = parts.length;
  1320. let cur = '';
  1321. for (; i < l; i++) {
  1322. const next = i + 1;
  1323. const last = next === l;
  1324. cur += (cur ? '.' + parts[i] : parts[i]);
  1325. if (specialProperties.has(parts[i])) {
  1326. return;
  1327. }
  1328. if (last) {
  1329. if (obj instanceof Map) {
  1330. obj.set(parts[i], val);
  1331. } else {
  1332. obj[parts[i]] = val;
  1333. }
  1334. } else {
  1335. if (utils.isPOJO(obj[parts[i]])) {
  1336. obj = obj[parts[i]];
  1337. } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) {
  1338. obj = obj[parts[i]];
  1339. } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) {
  1340. obj = obj[parts[i]];
  1341. } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
  1342. obj = obj[parts[i]];
  1343. } else {
  1344. obj[parts[i]] = obj[parts[i]] || {};
  1345. obj = obj[parts[i]];
  1346. }
  1347. }
  1348. }
  1349. };
  1350. /**
  1351. * Gets a raw value from a path (no getters)
  1352. *
  1353. * @param {String} path
  1354. * @api private
  1355. */
  1356. Document.prototype.$__getValue = function(path) {
  1357. return utils.getValue(path, this._doc);
  1358. };
  1359. /**
  1360. * Sets a raw value for a path (no casting, setters, transformations)
  1361. *
  1362. * @param {String} path
  1363. * @param {Object} value
  1364. * @api private
  1365. */
  1366. Document.prototype.$__setValue = function(path, val) {
  1367. utils.setValue(path, val, this._doc);
  1368. return this;
  1369. };
  1370. /**
  1371. * Returns the value of a path.
  1372. *
  1373. * ####Example
  1374. *
  1375. * // path
  1376. * doc.get('age') // 47
  1377. *
  1378. * // dynamic casting to a string
  1379. * doc.get('age', String) // "47"
  1380. *
  1381. * @param {String} path
  1382. * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes
  1383. * @param {Object} [options]
  1384. * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path
  1385. * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value
  1386. * @api public
  1387. */
  1388. Document.prototype.get = function(path, type, options) {
  1389. let adhoc;
  1390. options = options || {};
  1391. if (type) {
  1392. adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options);
  1393. }
  1394. let schema = this.$__path(path);
  1395. if (schema == null) {
  1396. schema = this.$__schema.virtualpath(path);
  1397. }
  1398. if (schema instanceof MixedSchema) {
  1399. const virtual = this.$__schema.virtualpath(path);
  1400. if (virtual != null) {
  1401. schema = virtual;
  1402. }
  1403. }
  1404. const pieces = path.indexOf('.') === -1 ? [path] : path.split('.');
  1405. let obj = this._doc;
  1406. if (schema instanceof VirtualType) {
  1407. return schema.applyGetters(void 0, this);
  1408. }
  1409. // Might need to change path for top-level alias
  1410. if (typeof this.$__schema.aliases[pieces[0]] == 'string') {
  1411. pieces[0] = this.$__schema.aliases[pieces[0]];
  1412. }
  1413. for (let i = 0, l = pieces.length; i < l; i++) {
  1414. if (obj && obj._doc) {
  1415. obj = obj._doc;
  1416. }
  1417. if (obj == null) {
  1418. obj = void 0;
  1419. } else if (obj instanceof Map) {
  1420. obj = obj.get(pieces[i], { getters: false });
  1421. } else if (i === l - 1) {
  1422. obj = utils.getValue(pieces[i], obj);
  1423. } else {
  1424. obj = obj[pieces[i]];
  1425. }
  1426. }
  1427. if (adhoc) {
  1428. obj = adhoc.cast(obj);
  1429. }
  1430. if (schema != null && options.getters !== false) {
  1431. obj = schema.applyGetters(obj, this);
  1432. } else if (this.$__schema.nested[path] && options.virtuals) {
  1433. // Might need to apply virtuals if this is a nested path
  1434. return applyVirtuals(this, utils.clone(obj) || {}, { path: path });
  1435. }
  1436. return obj;
  1437. };
  1438. /*!
  1439. * ignore
  1440. */
  1441. Document.prototype[getSymbol] = Document.prototype.get;
  1442. /**
  1443. * Returns the schematype for the given `path`.
  1444. *
  1445. * @param {String} path
  1446. * @api private
  1447. * @method $__path
  1448. * @memberOf Document
  1449. * @instance
  1450. */
  1451. Document.prototype.$__path = function(path) {
  1452. const adhocs = this.$__.adhocPaths;
  1453. const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null;
  1454. if (adhocType) {
  1455. return adhocType;
  1456. }
  1457. return this.$__schema.path(path);
  1458. };
  1459. /**
  1460. * Marks the path as having pending changes to write to the db.
  1461. *
  1462. * _Very helpful when using [Mixed](./schematypes.html#mixed) types._
  1463. *
  1464. * ####Example:
  1465. *
  1466. * doc.mixed.type = 'changed';
  1467. * doc.markModified('mixed.type');
  1468. * doc.save() // changes to mixed.type are now persisted
  1469. *
  1470. * @param {String} path the path to mark modified
  1471. * @param {Document} [scope] the scope to run validators with
  1472. * @api public
  1473. */
  1474. Document.prototype.markModified = function(path, scope) {
  1475. this.$__.activePaths.modify(path);
  1476. if (scope != null && !this.ownerDocument) {
  1477. this.$__.pathsToScopes[path] = scope;
  1478. }
  1479. };
  1480. /**
  1481. * Clears the modified state on the specified path.
  1482. *
  1483. * ####Example:
  1484. *
  1485. * doc.foo = 'bar';
  1486. * doc.unmarkModified('foo');
  1487. * doc.save(); // changes to foo will not be persisted
  1488. *
  1489. * @param {String} path the path to unmark modified
  1490. * @api public
  1491. */
  1492. Document.prototype.unmarkModified = function(path) {
  1493. this.$__.activePaths.init(path);
  1494. delete this.$__.pathsToScopes[path];
  1495. };
  1496. /**
  1497. * Don't run validation on this path or persist changes to this path.
  1498. *
  1499. * ####Example:
  1500. *
  1501. * doc.foo = null;
  1502. * doc.$ignore('foo');
  1503. * doc.save(); // changes to foo will not be persisted and validators won't be run
  1504. *
  1505. * @memberOf Document
  1506. * @instance
  1507. * @method $ignore
  1508. * @param {String} path the path to ignore
  1509. * @api public
  1510. */
  1511. Document.prototype.$ignore = function(path) {
  1512. this.$__.activePaths.ignore(path);
  1513. };
  1514. /**
  1515. * Returns the list of paths that have been directly modified. A direct
  1516. * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`,
  1517. * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`.
  1518. *
  1519. * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()`
  1520. * because a child of `a` was directly modified.
  1521. *
  1522. * ####Example
  1523. * const schema = new Schema({ foo: String, nested: { bar: String } });
  1524. * const Model = mongoose.model('Test', schema);
  1525. * await Model.create({ foo: 'original', nested: { bar: 'original' } });
  1526. *
  1527. * const doc = await Model.findOne();
  1528. * doc.nested.bar = 'modified';
  1529. * doc.directModifiedPaths(); // ['nested.bar']
  1530. * doc.modifiedPaths(); // ['nested', 'nested.bar']
  1531. *
  1532. * @return {Array}
  1533. * @api public
  1534. */
  1535. Document.prototype.directModifiedPaths = function() {
  1536. return Object.keys(this.$__.activePaths.states.modify);
  1537. };
  1538. /**
  1539. * Returns true if the given path is nullish or only contains empty objects.
  1540. * Useful for determining whether this subdoc will get stripped out by the
  1541. * [minimize option](/docs/guide.html#minimize).
  1542. *
  1543. * ####Example:
  1544. * const schema = new Schema({ nested: { foo: String } });
  1545. * const Model = mongoose.model('Test', schema);
  1546. * const doc = new Model({});
  1547. * doc.$isEmpty('nested'); // true
  1548. * doc.nested.$isEmpty(); // true
  1549. *
  1550. * doc.nested.foo = 'bar';
  1551. * doc.$isEmpty('nested'); // false
  1552. * doc.nested.$isEmpty(); // false
  1553. *
  1554. * @memberOf Document
  1555. * @instance
  1556. * @api public
  1557. * @method $isEmpty
  1558. * @return {Boolean}
  1559. */
  1560. Document.prototype.$isEmpty = function(path) {
  1561. const isEmptyOptions = {
  1562. minimize: true,
  1563. virtuals: false,
  1564. getters: false,
  1565. transform: false
  1566. };
  1567. if (arguments.length > 0) {
  1568. const v = this.get(path);
  1569. if (v == null) {
  1570. return true;
  1571. }
  1572. if (typeof v !== 'object') {
  1573. return false;
  1574. }
  1575. if (utils.isPOJO(v)) {
  1576. return _isEmpty(v);
  1577. }
  1578. return Object.keys(v.toObject(isEmptyOptions)).length === 0;
  1579. }
  1580. return Object.keys(this.toObject(isEmptyOptions)).length === 0;
  1581. };
  1582. function _isEmpty(v) {
  1583. if (v == null) {
  1584. return true;
  1585. }
  1586. if (typeof v !== 'object' || Array.isArray(v)) {
  1587. return false;
  1588. }
  1589. for (const key of Object.keys(v)) {
  1590. if (!_isEmpty(v[key])) {
  1591. return false;
  1592. }
  1593. }
  1594. return true;
  1595. }
  1596. /**
  1597. * Returns the list of paths that have been modified.
  1598. *
  1599. * @param {Object} [options]
  1600. * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`.
  1601. * @return {Array}
  1602. * @api public
  1603. */
  1604. Document.prototype.modifiedPaths = function(options) {
  1605. options = options || {};
  1606. const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
  1607. const _this = this;
  1608. return directModifiedPaths.reduce(function(list, path) {
  1609. const parts = path.split('.');
  1610. list = list.concat(parts.reduce(function(chains, part, i) {
  1611. return chains.concat(parts.slice(0, i).concat(part).join('.'));
  1612. }, []).filter(function(chain) {
  1613. return (list.indexOf(chain) === -1);
  1614. }));
  1615. if (!options.includeChildren) {
  1616. return list;
  1617. }
  1618. let cur = _this.get(path);
  1619. if (cur != null && typeof cur === 'object') {
  1620. if (cur._doc) {
  1621. cur = cur._doc;
  1622. }
  1623. if (Array.isArray(cur)) {
  1624. const len = cur.length;
  1625. for (let i = 0; i < len; ++i) {
  1626. if (list.indexOf(path + '.' + i) === -1) {
  1627. list.push(path + '.' + i);
  1628. if (cur[i] != null && cur[i].$__) {
  1629. const modified = cur[i].modifiedPaths();
  1630. for (const childPath of modified) {
  1631. list.push(path + '.' + i + '.' + childPath);
  1632. }
  1633. }
  1634. }
  1635. }
  1636. } else {
  1637. Object.keys(cur).
  1638. filter(function(key) {
  1639. return list.indexOf(path + '.' + key) === -1;
  1640. }).
  1641. forEach(function(key) {
  1642. list.push(path + '.' + key);
  1643. });
  1644. }
  1645. }
  1646. return list;
  1647. }, []);
  1648. };
  1649. Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths;
  1650. /**
  1651. * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path
  1652. * in this document is modified.
  1653. *
  1654. * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified.
  1655. *
  1656. * ####Example
  1657. *
  1658. * doc.set('documents.0.title', 'changed');
  1659. * doc.isModified() // true
  1660. * doc.isModified('documents') // true
  1661. * doc.isModified('documents.0.title') // true
  1662. * doc.isModified('documents otherProp') // true
  1663. * doc.isDirectModified('documents') // false
  1664. *
  1665. * @param {String} [path] optional
  1666. * @return {Boolean}
  1667. * @api public
  1668. */
  1669. Document.prototype.isModified = function(paths, modifiedPaths) {
  1670. if (paths) {
  1671. if (!Array.isArray(paths)) {
  1672. paths = paths.split(' ');
  1673. }
  1674. const modified = modifiedPaths || this[documentModifiedPaths]();
  1675. const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
  1676. const isModifiedChild = paths.some(function(path) {
  1677. return !!~modified.indexOf(path);
  1678. });
  1679. return isModifiedChild || paths.some(function(path) {
  1680. return directModifiedPaths.some(function(mod) {
  1681. return mod === path || path.startsWith(mod + '.');
  1682. });
  1683. });
  1684. }
  1685. return this.$__.activePaths.some('modify');
  1686. };
  1687. Document.prototype[documentIsModified] = Document.prototype.isModified;
  1688. /**
  1689. * Checks if a path is set to its default.
  1690. *
  1691. * ####Example
  1692. *
  1693. * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
  1694. * const m = new MyModel();
  1695. * m.$isDefault('name'); // true
  1696. *
  1697. * @memberOf Document
  1698. * @instance
  1699. * @method $isDefault
  1700. * @param {String} [path]
  1701. * @return {Boolean}
  1702. * @api public
  1703. */
  1704. Document.prototype.$isDefault = function(path) {
  1705. if (path == null) {
  1706. return this.$__.activePaths.some('default');
  1707. }
  1708. if (typeof path === 'string' && path.indexOf(' ') === -1) {
  1709. return this.$__.activePaths.states.default.hasOwnProperty(path);
  1710. }
  1711. let paths = path;
  1712. if (!Array.isArray(paths)) {
  1713. paths = paths.split(' ');
  1714. }
  1715. return paths.some(path => this.$__.activePaths.states.default.hasOwnProperty(path));
  1716. };
  1717. /**
  1718. * Getter/setter, determines whether the document was removed or not.
  1719. *
  1720. * ####Example:
  1721. * product.remove(function (err, product) {
  1722. * product.$isDeleted(); // true
  1723. * product.remove(); // no-op, doesn't send anything to the db
  1724. *
  1725. * product.$isDeleted(false);
  1726. * product.$isDeleted(); // false
  1727. * product.remove(); // will execute a remove against the db
  1728. * })
  1729. *
  1730. * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted
  1731. * @return {Boolean} whether mongoose thinks this doc is deleted.
  1732. * @method $isDeleted
  1733. * @memberOf Document
  1734. * @instance
  1735. * @api public
  1736. */
  1737. Document.prototype.$isDeleted = function(val) {
  1738. if (arguments.length === 0) {
  1739. return !!this.$__.isDeleted;
  1740. }
  1741. this.$__.isDeleted = !!val;
  1742. return this;
  1743. };
  1744. /**
  1745. * Returns true if `path` was directly set and modified, else false.
  1746. *
  1747. * ####Example
  1748. *
  1749. * doc.set('documents.0.title', 'changed');
  1750. * doc.isDirectModified('documents.0.title') // true
  1751. * doc.isDirectModified('documents') // false
  1752. *
  1753. * @param {String|Array<String>} path
  1754. * @return {Boolean}
  1755. * @api public
  1756. */
  1757. Document.prototype.isDirectModified = function(path) {
  1758. if (path == null) {
  1759. return this.$__.activePaths.some('modify');
  1760. }
  1761. if (typeof path === 'string' && path.indexOf(' ') === -1) {
  1762. return this.$__.activePaths.states.modify.hasOwnProperty(path);
  1763. }
  1764. let paths = path;
  1765. if (!Array.isArray(paths)) {
  1766. paths = paths.split(' ');
  1767. }
  1768. return paths.some(path => this.$__.activePaths.states.modify.hasOwnProperty(path));
  1769. };
  1770. /**
  1771. * Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since.
  1772. *
  1773. * @param {String} path
  1774. * @return {Boolean}
  1775. * @api public
  1776. */
  1777. Document.prototype.isInit = function(path) {
  1778. if (path == null) {
  1779. return this.$__.activePaths.some('init');
  1780. }
  1781. if (typeof path === 'string' && path.indexOf(' ') === -1) {
  1782. return this.$__.activePaths.states.init.hasOwnProperty(path);
  1783. }
  1784. let paths = path;
  1785. if (!Array.isArray(paths)) {
  1786. paths = paths.split(' ');
  1787. }
  1788. return paths.some(path => this.$__.activePaths.states.init.hasOwnProperty(path));
  1789. };
  1790. /**
  1791. * Checks if `path` was selected in the source query which initialized this document.
  1792. *
  1793. * ####Example
  1794. *
  1795. * Thing.findOne().select('name').exec(function (err, doc) {
  1796. * doc.isSelected('name') // true
  1797. * doc.isSelected('age') // false
  1798. * })
  1799. *
  1800. * @param {String|Array<String>} path
  1801. * @return {Boolean}
  1802. * @api public
  1803. */
  1804. Document.prototype.isSelected = function isSelected(path) {
  1805. if (this.$__.selected == null) {
  1806. return true;
  1807. }
  1808. if (path === '_id') {
  1809. return this.$__.selected._id !== 0;
  1810. }
  1811. if (path.indexOf(' ') !== -1) {
  1812. path = path.split(' ');
  1813. }
  1814. if (Array.isArray(path)) {
  1815. return path.some(p => this.$__isSelected(p));
  1816. }
  1817. const paths = Object.keys(this.$__.selected);
  1818. let inclusive = null;
  1819. if (paths.length === 1 && paths[0] === '_id') {
  1820. // only _id was selected.
  1821. return this.$__.selected._id === 0;
  1822. }
  1823. for (const cur of paths) {
  1824. if (cur === '_id') {
  1825. continue;
  1826. }
  1827. if (!isDefiningProjection(this.$__.selected[cur])) {
  1828. continue;
  1829. }
  1830. inclusive = !!this.$__.selected[cur];
  1831. break;
  1832. }
  1833. if (inclusive === null) {
  1834. return true;
  1835. }
  1836. if (path in this.$__.selected) {
  1837. return inclusive;
  1838. }
  1839. const pathDot = path + '.';
  1840. for (const cur of paths) {
  1841. if (cur === '_id') {
  1842. continue;
  1843. }
  1844. if (cur.startsWith(pathDot)) {
  1845. return inclusive || cur !== pathDot;
  1846. }
  1847. if (pathDot.startsWith(cur + '.')) {
  1848. return inclusive;
  1849. }
  1850. }
  1851. return !inclusive;
  1852. };
  1853. Document.prototype.$__isSelected = Document.prototype.isSelected;
  1854. /**
  1855. * Checks if `path` was explicitly selected. If no projection, always returns
  1856. * true.
  1857. *
  1858. * ####Example
  1859. *
  1860. * Thing.findOne().select('nested.name').exec(function (err, doc) {
  1861. * doc.isDirectSelected('nested.name') // true
  1862. * doc.isDirectSelected('nested.otherName') // false
  1863. * doc.isDirectSelected('nested') // false
  1864. * })
  1865. *
  1866. * @param {String} path
  1867. * @return {Boolean}
  1868. * @api public
  1869. */
  1870. Document.prototype.isDirectSelected = function isDirectSelected(path) {
  1871. if (this.$__.selected == null) {
  1872. return true;
  1873. }
  1874. if (path === '_id') {
  1875. return this.$__.selected._id !== 0;
  1876. }
  1877. if (path.indexOf(' ') !== -1) {
  1878. path = path.split(' ');
  1879. }
  1880. if (Array.isArray(path)) {
  1881. return path.some(p => this.isDirectSelected(p));
  1882. }
  1883. const paths = Object.keys(this.$__.selected);
  1884. let inclusive = null;
  1885. if (paths.length === 1 && paths[0] === '_id') {
  1886. // only _id was selected.
  1887. return this.$__.selected._id === 0;
  1888. }
  1889. for (const cur of paths) {
  1890. if (cur === '_id') {
  1891. continue;
  1892. }
  1893. if (!isDefiningProjection(this.$__.selected[cur])) {
  1894. continue;
  1895. }
  1896. inclusive = !!this.$__.selected[cur];
  1897. break;
  1898. }
  1899. if (inclusive === null) {
  1900. return true;
  1901. }
  1902. if (this.$__.selected.hasOwnProperty(path)) {
  1903. return inclusive;
  1904. }
  1905. return !inclusive;
  1906. };
  1907. /**
  1908. * Executes registered validation rules for this document.
  1909. *
  1910. * ####Note:
  1911. *
  1912. * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`.
  1913. *
  1914. * ####Example:
  1915. *
  1916. * doc.validate(function (err) {
  1917. * if (err) handleError(err);
  1918. * else // validation passed
  1919. * });
  1920. *
  1921. * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list.
  1922. * @param {Object} [options] internal options
  1923. * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths.
  1924. * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred
  1925. * @return {Promise} Promise
  1926. * @api public
  1927. */
  1928. Document.prototype.validate = function(pathsToValidate, options, callback) {
  1929. let parallelValidate;
  1930. this.$op = 'validate';
  1931. if (this.ownerDocument != null) {
  1932. // Skip parallel validate check for subdocuments
  1933. } else if (this.$__.validating) {
  1934. parallelValidate = new ParallelValidateError(this, {
  1935. parentStack: options && options.parentStack,
  1936. conflictStack: this.$__.validating.stack
  1937. });
  1938. } else {
  1939. this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack });
  1940. }
  1941. if (arguments.length === 1) {
  1942. if (typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) {
  1943. options = arguments[0];
  1944. callback = null;
  1945. pathsToValidate = null;
  1946. } else if (typeof arguments[0] === 'function') {
  1947. callback = arguments[0];
  1948. options = null;
  1949. pathsToValidate = null;
  1950. }
  1951. } else if (typeof pathsToValidate === 'function') {
  1952. callback = pathsToValidate;
  1953. options = null;
  1954. pathsToValidate = null;
  1955. } else if (typeof options === 'function') {
  1956. callback = options;
  1957. options = pathsToValidate;
  1958. pathsToValidate = null;
  1959. }
  1960. return promiseOrCallback(callback, cb => {
  1961. if (parallelValidate != null) {
  1962. return cb(parallelValidate);
  1963. }
  1964. this.$__validate(pathsToValidate, options, (error) => {
  1965. this.$op = null;
  1966. cb(error);
  1967. });
  1968. }, this.constructor.events);
  1969. };
  1970. /*!
  1971. * ignore
  1972. */
  1973. function _evaluateRequiredFunctions(doc) {
  1974. Object.keys(doc.$__.activePaths.states.require).forEach(path => {
  1975. const p = doc.$__schema.path(path);
  1976. if (p != null && typeof p.originalRequiredValue === 'function') {
  1977. doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc);
  1978. }
  1979. });
  1980. }
  1981. /*!
  1982. * ignore
  1983. */
  1984. function _getPathsToValidate(doc) {
  1985. const skipSchemaValidators = {};
  1986. _evaluateRequiredFunctions(doc);
  1987. // only validate required fields when necessary
  1988. let paths = new Set(Object.keys(doc.$__.activePaths.states.require).filter(function(path) {
  1989. if (!doc.$__isSelected(path) && !doc.isModified(path)) {
  1990. return false;
  1991. }
  1992. if (path in doc.$__.cachedRequired) {
  1993. return doc.$__.cachedRequired[path];
  1994. }
  1995. return true;
  1996. }));
  1997. Object.keys(doc.$__.activePaths.states.init).forEach(addToPaths);
  1998. Object.keys(doc.$__.activePaths.states.modify).forEach(addToPaths);
  1999. Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths);
  2000. function addToPaths(p) { paths.add(p); }
  2001. const subdocs = doc.$getAllSubdocs();
  2002. const modifiedPaths = doc.modifiedPaths();
  2003. for (const subdoc of subdocs) {
  2004. if (subdoc.$basePath) {
  2005. // Remove child paths for now, because we'll be validating the whole
  2006. // subdoc
  2007. for (const p of paths) {
  2008. if (p === null || p.startsWith(subdoc.$basePath + '.')) {
  2009. paths.delete(p);
  2010. }
  2011. }
  2012. if (doc.isModified(subdoc.$basePath, modifiedPaths) &&
  2013. !doc.isDirectModified(subdoc.$basePath) &&
  2014. !doc.$isDefault(subdoc.$basePath)) {
  2015. paths.add(subdoc.$basePath);
  2016. skipSchemaValidators[subdoc.$basePath] = true;
  2017. }
  2018. }
  2019. }
  2020. // from here on we're not removing items from paths
  2021. // gh-661: if a whole array is modified, make sure to run validation on all
  2022. // the children as well
  2023. for (const path of paths) {
  2024. const _pathType = doc.$__schema.path(path);
  2025. if (!_pathType ||
  2026. !_pathType.$isMongooseArray ||
  2027. // To avoid potential performance issues, skip doc arrays whose children
  2028. // are not required. `getPositionalPathType()` may be slow, so avoid
  2029. // it unless we have a case of #6364
  2030. (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) {
  2031. continue;
  2032. }
  2033. const val = doc.$__getValue(path);
  2034. _pushNestedArrayPaths(val, paths, path);
  2035. }
  2036. function _pushNestedArrayPaths(val, paths, path) {
  2037. if (val != null) {
  2038. const numElements = val.length;
  2039. for (let j = 0; j < numElements; ++j) {
  2040. if (Array.isArray(val[j])) {
  2041. _pushNestedArrayPaths(val[j], paths, path + '.' + j);
  2042. } else {
  2043. paths.add(path + '.' + j);
  2044. }
  2045. }
  2046. }
  2047. }
  2048. const flattenOptions = { skipArrays: true };
  2049. for (const pathToCheck of paths) {
  2050. if (doc.$__schema.nested[pathToCheck]) {
  2051. let _v = doc.$__getValue(pathToCheck);
  2052. if (isMongooseObject(_v)) {
  2053. _v = _v.toObject({ transform: false });
  2054. }
  2055. const flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema);
  2056. Object.keys(flat).forEach(addToPaths);
  2057. }
  2058. }
  2059. for (const path of paths) {
  2060. // Single nested paths (paths embedded under single nested subdocs) will
  2061. // be validated on their own when we call `validate()` on the subdoc itself.
  2062. // Re: gh-8468
  2063. if (doc.$__schema.singleNestedPaths.hasOwnProperty(path)) {
  2064. paths.delete(path);
  2065. continue;
  2066. }
  2067. const _pathType = doc.$__schema.path(path);
  2068. if (!_pathType || !_pathType.$isSchemaMap) {
  2069. continue;
  2070. }
  2071. const val = doc.$__getValue(path);
  2072. if (val == null) {
  2073. continue;
  2074. }
  2075. for (const key of val.keys()) {
  2076. paths.add(path + '.' + key);
  2077. }
  2078. }
  2079. paths = Array.from(paths);
  2080. return [paths, skipSchemaValidators];
  2081. }
  2082. /*!
  2083. * ignore
  2084. */
  2085. Document.prototype.$__validate = function(pathsToValidate, options, callback) {
  2086. if (typeof pathsToValidate === 'function') {
  2087. callback = pathsToValidate;
  2088. options = null;
  2089. pathsToValidate = null;
  2090. } else if (typeof options === 'function') {
  2091. callback = options;
  2092. options = null;
  2093. }
  2094. const hasValidateModifiedOnlyOption = options &&
  2095. (typeof options === 'object') &&
  2096. ('validateModifiedOnly' in options);
  2097. let shouldValidateModifiedOnly;
  2098. if (hasValidateModifiedOnlyOption) {
  2099. shouldValidateModifiedOnly = !!options.validateModifiedOnly;
  2100. } else {
  2101. shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly;
  2102. }
  2103. const _this = this;
  2104. const _complete = () => {
  2105. let validationError = this.$__.validationError;
  2106. this.$__.validationError = undefined;
  2107. if (shouldValidateModifiedOnly && validationError != null) {
  2108. // Remove any validation errors that aren't from modified paths
  2109. const errors = Object.keys(validationError.errors);
  2110. for (const errPath of errors) {
  2111. if (!this.isModified(errPath)) {
  2112. delete validationError.errors[errPath];
  2113. }
  2114. }
  2115. if (Object.keys(validationError.errors).length === 0) {
  2116. validationError = void 0;
  2117. }
  2118. }
  2119. this.$__.cachedRequired = {};
  2120. this.emit('validate', _this);
  2121. this.constructor.emit('validate', _this);
  2122. this.$__.validating = null;
  2123. if (validationError) {
  2124. for (const key in validationError.errors) {
  2125. // Make sure cast errors persist
  2126. if (!this[documentArrayParent] &&
  2127. validationError.errors[key] instanceof MongooseError.CastError) {
  2128. this.invalidate(key, validationError.errors[key]);
  2129. }
  2130. }
  2131. return validationError;
  2132. }
  2133. };
  2134. // only validate required fields when necessary
  2135. const pathDetails = _getPathsToValidate(this);
  2136. let paths = shouldValidateModifiedOnly ?
  2137. pathDetails[0].filter((path) => this.isModified(path)) :
  2138. pathDetails[0];
  2139. const skipSchemaValidators = pathDetails[1];
  2140. if (typeof pathsToValidate === 'string') {
  2141. pathsToValidate = pathsToValidate.split(' ');
  2142. }
  2143. if (Array.isArray(pathsToValidate)) {
  2144. paths = _handlePathsToValidate(paths, pathsToValidate);
  2145. }
  2146. if (paths.length === 0) {
  2147. return immediate(function() {
  2148. const error = _complete();
  2149. if (error) {
  2150. return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
  2151. callback(error);
  2152. });
  2153. }
  2154. callback(null, _this);
  2155. });
  2156. }
  2157. const validated = {};
  2158. let total = 0;
  2159. const complete = function() {
  2160. const error = _complete();
  2161. if (error) {
  2162. return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) {
  2163. callback(error);
  2164. });
  2165. }
  2166. callback(null, _this);
  2167. };
  2168. const validatePath = function(path) {
  2169. if (path == null || validated[path]) {
  2170. return;
  2171. }
  2172. validated[path] = true;
  2173. total++;
  2174. immediate(function() {
  2175. const schemaType = _this.$__schema.path(path);
  2176. if (!schemaType) {
  2177. return --total || complete();
  2178. }
  2179. // If user marked as invalid or there was a cast error, don't validate
  2180. if (!_this.$isValid(path)) {
  2181. --total || complete();
  2182. return;
  2183. }
  2184. // If setting a path under a mixed path, avoid using the mixed path validator (gh-10141)
  2185. if (schemaType[schemaMixedSymbol] != null && path !== schemaType.path) {
  2186. return --total || complete();
  2187. }
  2188. let val = _this.$__getValue(path);
  2189. // If you `populate()` and get back a null value, required validators
  2190. // shouldn't fail (gh-8018). We should always fall back to the populated
  2191. // value.
  2192. let pop;
  2193. if (val == null && (pop = _this.populated(path))) {
  2194. val = pop;
  2195. }
  2196. const scope = path in _this.$__.pathsToScopes ?
  2197. _this.$__.pathsToScopes[path] :
  2198. _this;
  2199. const doValidateOptions = {
  2200. skipSchemaValidators: skipSchemaValidators[path],
  2201. path: path,
  2202. validateModifiedOnly: shouldValidateModifiedOnly
  2203. };
  2204. schemaType.doValidate(val, function(err) {
  2205. if (err && (!schemaType.$isMongooseDocumentArray || err.$isArrayValidatorError)) {
  2206. if (schemaType.$isSingleNested &&
  2207. err instanceof ValidationError &&
  2208. schemaType.schema.options.storeSubdocValidationError === false) {
  2209. return --total || complete();
  2210. }
  2211. _this.invalidate(path, err, undefined, true);
  2212. }
  2213. --total || complete();
  2214. }, scope, doValidateOptions);
  2215. });
  2216. };
  2217. const numPaths = paths.length;
  2218. for (let i = 0; i < numPaths; ++i) {
  2219. validatePath(paths[i]);
  2220. }
  2221. };
  2222. /*!
  2223. * ignore
  2224. */
  2225. function _handlePathsToValidate(paths, pathsToValidate) {
  2226. const _pathsToValidate = new Set(pathsToValidate);
  2227. const parentPaths = new Map([]);
  2228. for (const path of pathsToValidate) {
  2229. if (path.indexOf('.') === -1) {
  2230. continue;
  2231. }
  2232. const pieces = path.split('.');
  2233. let cur = pieces[0];
  2234. for (let i = 1; i < pieces.length; ++i) {
  2235. // Since we skip subpaths under single nested subdocs to
  2236. // avoid double validation, we need to add back the
  2237. // single nested subpath if the user asked for it (gh-8626)
  2238. parentPaths.set(cur, path);
  2239. cur = cur + '.' + pieces[i];
  2240. }
  2241. }
  2242. const ret = [];
  2243. for (const path of paths) {
  2244. if (_pathsToValidate.has(path)) {
  2245. ret.push(path);
  2246. } else if (parentPaths.has(path)) {
  2247. ret.push(parentPaths.get(path));
  2248. }
  2249. }
  2250. return ret;
  2251. }
  2252. /**
  2253. * Executes registered validation rules (skipping asynchronous validators) for this document.
  2254. *
  2255. * ####Note:
  2256. *
  2257. * This method is useful if you need synchronous validation.
  2258. *
  2259. * ####Example:
  2260. *
  2261. * const err = doc.validateSync();
  2262. * if (err) {
  2263. * handleError(err);
  2264. * } else {
  2265. * // validation passed
  2266. * }
  2267. *
  2268. * @param {Array|string} pathsToValidate only validate the given paths
  2269. * @param {Object} [options] options for validation
  2270. * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths.
  2271. * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error.
  2272. * @api public
  2273. */
  2274. Document.prototype.validateSync = function(pathsToValidate, options) {
  2275. const _this = this;
  2276. if (arguments.length === 1 && typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) {
  2277. options = arguments[0];
  2278. pathsToValidate = null;
  2279. }
  2280. const hasValidateModifiedOnlyOption = options &&
  2281. (typeof options === 'object') &&
  2282. ('validateModifiedOnly' in options);
  2283. let shouldValidateModifiedOnly;
  2284. if (hasValidateModifiedOnlyOption) {
  2285. shouldValidateModifiedOnly = !!options.validateModifiedOnly;
  2286. } else {
  2287. shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly;
  2288. }
  2289. if (typeof pathsToValidate === 'string') {
  2290. pathsToValidate = pathsToValidate.split(' ');
  2291. }
  2292. // only validate required fields when necessary
  2293. const pathDetails = _getPathsToValidate(this);
  2294. let paths = shouldValidateModifiedOnly ?
  2295. pathDetails[0].filter((path) => this.isModified(path)) :
  2296. pathDetails[0];
  2297. const skipSchemaValidators = pathDetails[1];
  2298. if (typeof pathsToValidate === 'string') {
  2299. pathsToValidate = pathsToValidate.split(' ');
  2300. }
  2301. if (Array.isArray(pathsToValidate)) {
  2302. paths = _handlePathsToValidate(paths, pathsToValidate);
  2303. }
  2304. const validating = {};
  2305. paths.forEach(function(path) {
  2306. if (validating[path]) {
  2307. return;
  2308. }
  2309. validating[path] = true;
  2310. const p = _this.$__schema.path(path);
  2311. if (!p) {
  2312. return;
  2313. }
  2314. if (!_this.$isValid(path)) {
  2315. return;
  2316. }
  2317. const val = _this.$__getValue(path);
  2318. const err = p.doValidateSync(val, _this, {
  2319. skipSchemaValidators: skipSchemaValidators[path],
  2320. path: path,
  2321. validateModifiedOnly: shouldValidateModifiedOnly
  2322. });
  2323. if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) {
  2324. if (p.$isSingleNested &&
  2325. err instanceof ValidationError &&
  2326. p.schema.options.storeSubdocValidationError === false) {
  2327. return;
  2328. }
  2329. _this.invalidate(path, err, undefined, true);
  2330. }
  2331. });
  2332. const err = _this.$__.validationError;
  2333. _this.$__.validationError = undefined;
  2334. _this.emit('validate', _this);
  2335. _this.constructor.emit('validate', _this);
  2336. if (err) {
  2337. for (const key in err.errors) {
  2338. // Make sure cast errors persist
  2339. if (err.errors[key] instanceof MongooseError.CastError) {
  2340. _this.invalidate(key, err.errors[key]);
  2341. }
  2342. }
  2343. }
  2344. return err;
  2345. };
  2346. /**
  2347. * Marks a path as invalid, causing validation to fail.
  2348. *
  2349. * The `errorMsg` argument will become the message of the `ValidationError`.
  2350. *
  2351. * The `value` argument (if passed) will be available through the `ValidationError.value` property.
  2352. *
  2353. * doc.invalidate('size', 'must be less than 20', 14);
  2354. * doc.validate(function (err) {
  2355. * console.log(err)
  2356. * // prints
  2357. * { message: 'Validation failed',
  2358. * name: 'ValidationError',
  2359. * errors:
  2360. * { size:
  2361. * { message: 'must be less than 20',
  2362. * name: 'ValidatorError',
  2363. * path: 'size',
  2364. * type: 'user defined',
  2365. * value: 14 } } }
  2366. * })
  2367. *
  2368. * @param {String} path the field to invalidate. For array elements, use the `array.i.field` syntax, where `i` is the 0-based index in the array.
  2369. * @param {String|Error} errorMsg the error which states the reason `path` was invalid
  2370. * @param {Object|String|Number|any} value optional invalid value
  2371. * @param {String} [kind] optional `kind` property for the error
  2372. * @return {ValidationError} the current ValidationError, with all currently invalidated paths
  2373. * @api public
  2374. */
  2375. Document.prototype.invalidate = function(path, err, val, kind) {
  2376. if (!this.$__.validationError) {
  2377. this.$__.validationError = new ValidationError(this);
  2378. }
  2379. if (this.$__.validationError.errors[path]) {
  2380. return;
  2381. }
  2382. if (!err || typeof err === 'string') {
  2383. err = new ValidatorError({
  2384. path: path,
  2385. message: err,
  2386. type: kind || 'user defined',
  2387. value: val
  2388. });
  2389. }
  2390. if (this.$__.validationError === err) {
  2391. return this.$__.validationError;
  2392. }
  2393. this.$__.validationError.addError(path, err);
  2394. return this.$__.validationError;
  2395. };
  2396. /**
  2397. * Marks a path as valid, removing existing validation errors.
  2398. *
  2399. * @param {String} path the field to mark as valid
  2400. * @api public
  2401. * @memberOf Document
  2402. * @instance
  2403. * @method $markValid
  2404. */
  2405. Document.prototype.$markValid = function(path) {
  2406. if (!this.$__.validationError || !this.$__.validationError.errors[path]) {
  2407. return;
  2408. }
  2409. delete this.$__.validationError.errors[path];
  2410. if (Object.keys(this.$__.validationError.errors).length === 0) {
  2411. this.$__.validationError = null;
  2412. }
  2413. };
  2414. /*!
  2415. * ignore
  2416. */
  2417. function _markValidSubpaths(doc, path) {
  2418. if (!doc.$__.validationError) {
  2419. return;
  2420. }
  2421. const keys = Object.keys(doc.$__.validationError.errors);
  2422. for (const key of keys) {
  2423. if (key.startsWith(path + '.')) {
  2424. delete doc.$__.validationError.errors[key];
  2425. }
  2426. }
  2427. if (Object.keys(doc.$__.validationError.errors).length === 0) {
  2428. doc.$__.validationError = null;
  2429. }
  2430. }
  2431. /*!
  2432. * ignore
  2433. */
  2434. function _checkImmutableSubpaths(subdoc, schematype, priorVal) {
  2435. const schema = schematype.schema;
  2436. if (schema == null) {
  2437. return;
  2438. }
  2439. for (const key of Object.keys(schema.paths)) {
  2440. const path = schema.paths[key];
  2441. if (path.$immutableSetter == null) {
  2442. continue;
  2443. }
  2444. const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key);
  2445. // Calling immutableSetter with `oldVal` even though it expects `newVal`
  2446. // is intentional. That's because `$immutableSetter` compares its param
  2447. // to the current value.
  2448. path.$immutableSetter.call(subdoc, oldVal);
  2449. }
  2450. }
  2451. /**
  2452. * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`,
  2453. * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case.
  2454. *
  2455. * ####Example:
  2456. *
  2457. * product.sold = Date.now();
  2458. * product = await product.save();
  2459. *
  2460. * If save is successful, the returned promise will fulfill with the document
  2461. * saved.
  2462. *
  2463. * ####Example:
  2464. *
  2465. * const newProduct = await product.save();
  2466. * newProduct === product; // true
  2467. *
  2468. * @param {Object} [options] options optional options
  2469. * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session).
  2470. * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead.
  2471. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
  2472. * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths.
  2473. * @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)
  2474. * @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)
  2475. * @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).
  2476. * @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)
  2477. * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`.
  2478. * @param {Function} [fn] optional callback
  2479. * @method save
  2480. * @memberOf Document
  2481. * @instance
  2482. * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating).
  2483. * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise.
  2484. * @api public
  2485. * @see middleware http://mongoosejs.com/docs/middleware.html
  2486. */
  2487. /**
  2488. * Checks if a path is invalid
  2489. *
  2490. * @param {String|Array<String>} path the field to check
  2491. * @method $isValid
  2492. * @memberOf Document
  2493. * @instance
  2494. * @api private
  2495. */
  2496. Document.prototype.$isValid = function(path) {
  2497. if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) {
  2498. return true;
  2499. }
  2500. if (path == null) {
  2501. return false;
  2502. }
  2503. if (path.indexOf(' ') !== -1) {
  2504. path = path.split(' ');
  2505. }
  2506. if (Array.isArray(path)) {
  2507. return path.some(p => this.$__.validationError.errors[p] == null);
  2508. }
  2509. return this.$__.validationError.errors[path] == null;
  2510. };
  2511. /**
  2512. * Resets the internal modified state of this document.
  2513. *
  2514. * @api private
  2515. * @return {Document}
  2516. * @method $__reset
  2517. * @memberOf Document
  2518. * @instance
  2519. */
  2520. Document.prototype.$__reset = function reset() {
  2521. let _this = this;
  2522. DocumentArray || (DocumentArray = require('./types/documentarray'));
  2523. this.$__.activePaths
  2524. .map('init', 'modify', function(i) {
  2525. return _this.$__getValue(i);
  2526. })
  2527. .filter(function(val) {
  2528. return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
  2529. })
  2530. .forEach(function(array) {
  2531. let i = array.length;
  2532. while (i--) {
  2533. const doc = array[i];
  2534. if (!doc) {
  2535. continue;
  2536. }
  2537. doc.$__reset();
  2538. }
  2539. _this.$__.activePaths.init(array.$path());
  2540. array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol];
  2541. array[arrayAtomicsSymbol] = {};
  2542. });
  2543. this.$__.activePaths.
  2544. map('init', 'modify', function(i) {
  2545. return _this.$__getValue(i);
  2546. }).
  2547. filter(function(val) {
  2548. return val && val.$isSingleNested;
  2549. }).
  2550. forEach(function(doc) {
  2551. doc.$__reset();
  2552. if (doc.$__parent === _this) {
  2553. _this.$__.activePaths.init(doc.$basePath);
  2554. } else if (doc.$__parent != null) {
  2555. // If map path underneath nested path, may end up with a case where
  2556. // map path is modified but parent still needs to be reset. See gh-10295
  2557. doc.$__parent.$__reset();
  2558. }
  2559. });
  2560. // clear atomics
  2561. this.$__dirty().forEach(function(dirt) {
  2562. const type = dirt.value;
  2563. if (type && type[arrayAtomicsSymbol]) {
  2564. type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol];
  2565. type[arrayAtomicsSymbol] = {};
  2566. }
  2567. });
  2568. this.$__.backup = {};
  2569. this.$__.backup.activePaths = {
  2570. modify: Object.assign({}, this.$__.activePaths.states.modify),
  2571. default: Object.assign({}, this.$__.activePaths.states.default)
  2572. };
  2573. this.$__.backup.validationError = this.$__.validationError;
  2574. this.$__.backup.errors = this.errors;
  2575. // Clear 'dirty' cache
  2576. this.$__.activePaths.clear('modify');
  2577. this.$__.activePaths.clear('default');
  2578. this.$__.validationError = undefined;
  2579. this.errors = undefined;
  2580. _this = this;
  2581. this.$__schema.requiredPaths().forEach(function(path) {
  2582. _this.$__.activePaths.require(path);
  2583. });
  2584. return this;
  2585. };
  2586. /*!
  2587. * ignore
  2588. */
  2589. Document.prototype.$__undoReset = function $__undoReset() {
  2590. if (this.$__.backup == null || this.$__.backup.activePaths == null) {
  2591. return;
  2592. }
  2593. this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify;
  2594. this.$__.activePaths.states.default = this.$__.backup.activePaths.default;
  2595. this.$__.validationError = this.$__.backup.validationError;
  2596. this.errors = this.$__.backup.errors;
  2597. for (const dirt of this.$__dirty()) {
  2598. const type = dirt.value;
  2599. if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) {
  2600. type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol];
  2601. }
  2602. }
  2603. for (const subdoc of this.$getAllSubdocs()) {
  2604. subdoc.$__undoReset();
  2605. }
  2606. };
  2607. /**
  2608. * Returns this documents dirty paths / vals.
  2609. *
  2610. * @api private
  2611. * @method $__dirty
  2612. * @memberOf Document
  2613. * @instance
  2614. */
  2615. Document.prototype.$__dirty = function() {
  2616. const _this = this;
  2617. let all = this.$__.activePaths.map('modify', function(path) {
  2618. return {
  2619. path: path,
  2620. value: _this.$__getValue(path),
  2621. schema: _this.$__path(path)
  2622. };
  2623. });
  2624. // gh-2558: if we had to set a default and the value is not undefined,
  2625. // we have to save as well
  2626. all = all.concat(this.$__.activePaths.map('default', function(path) {
  2627. if (path === '_id' || _this.$__getValue(path) == null) {
  2628. return;
  2629. }
  2630. return {
  2631. path: path,
  2632. value: _this.$__getValue(path),
  2633. schema: _this.$__path(path)
  2634. };
  2635. }));
  2636. // Sort dirty paths in a flat hierarchy.
  2637. all.sort(function(a, b) {
  2638. return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0));
  2639. });
  2640. // Ignore "foo.a" if "foo" is dirty already.
  2641. const minimal = [];
  2642. let lastPath;
  2643. let top;
  2644. all.forEach(function(item) {
  2645. if (!item) {
  2646. return;
  2647. }
  2648. if (lastPath == null || item.path.indexOf(lastPath) !== 0) {
  2649. lastPath = item.path + '.';
  2650. minimal.push(item);
  2651. top = item;
  2652. } else if (top != null &&
  2653. top.value != null &&
  2654. top.value[arrayAtomicsSymbol] != null &&
  2655. top.value.hasAtomics()) {
  2656. // special case for top level MongooseArrays
  2657. // the `top` array itself and a sub path of `top` are being modified.
  2658. // the only way to honor all of both modifications is through a $set
  2659. // of entire array.
  2660. top.value[arrayAtomicsSymbol] = {};
  2661. top.value[arrayAtomicsSymbol].$set = top.value;
  2662. }
  2663. });
  2664. top = lastPath = null;
  2665. return minimal;
  2666. };
  2667. /**
  2668. * Assigns/compiles `schema` into this documents prototype.
  2669. *
  2670. * @param {Schema} schema
  2671. * @api private
  2672. * @method $__setSchema
  2673. * @memberOf Document
  2674. * @instance
  2675. */
  2676. Document.prototype.$__setSchema = function(schema) {
  2677. schema.plugin(idGetter, { deduplicate: true });
  2678. compile(schema.tree, this, undefined, schema.options);
  2679. // Apply default getters if virtual doesn't have any (gh-6262)
  2680. for (const key of Object.keys(schema.virtuals)) {
  2681. schema.virtuals[key]._applyDefaultGetters();
  2682. }
  2683. if (schema.path('schema') == null) {
  2684. this.schema = schema;
  2685. }
  2686. this.$__schema = schema;
  2687. this[documentSchemaSymbol] = schema;
  2688. };
  2689. /**
  2690. * Get active path that were changed and are arrays
  2691. *
  2692. * @api private
  2693. * @method $__getArrayPathsToValidate
  2694. * @memberOf Document
  2695. * @instance
  2696. */
  2697. Document.prototype.$__getArrayPathsToValidate = function() {
  2698. DocumentArray || (DocumentArray = require('./types/documentarray'));
  2699. // validate all document arrays.
  2700. return this.$__.activePaths
  2701. .map('init', 'modify', function(i) {
  2702. return this.$__getValue(i);
  2703. }.bind(this))
  2704. .filter(function(val) {
  2705. return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
  2706. }).reduce(function(seed, array) {
  2707. return seed.concat(array);
  2708. }, [])
  2709. .filter(function(doc) {
  2710. return doc;
  2711. });
  2712. };
  2713. /**
  2714. * Get all subdocs (by bfs)
  2715. *
  2716. * @api public
  2717. * @method $getAllSubdocs
  2718. * @memberOf Document
  2719. * @instance
  2720. */
  2721. Document.prototype.$getAllSubdocs = function $getAllSubdocs() {
  2722. DocumentArray || (DocumentArray = require('./types/documentarray'));
  2723. Embedded = Embedded || require('./types/embedded');
  2724. function docReducer(doc, seed, path) {
  2725. let val = doc;
  2726. let isNested = false;
  2727. if (path) {
  2728. if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) {
  2729. val = doc._doc[path];
  2730. } else if (doc instanceof Document && doc[documentSchemaSymbol].nested[path]) {
  2731. val = doc._doc[path];
  2732. isNested = true;
  2733. } else {
  2734. val = doc[path];
  2735. }
  2736. }
  2737. if (val instanceof Embedded) {
  2738. seed.push(val);
  2739. } else if (val instanceof Map) {
  2740. seed = Array.from(val.keys()).reduce(function(seed, path) {
  2741. return docReducer(val.get(path), seed, null);
  2742. }, seed);
  2743. } else if (val && val.$isSingleNested) {
  2744. seed = Object.keys(val._doc).reduce(function(seed, path) {
  2745. return docReducer(val._doc, seed, path);
  2746. }, seed);
  2747. seed.push(val);
  2748. } else if (val && val.isMongooseDocumentArray) {
  2749. val.forEach(function _docReduce(doc) {
  2750. if (!doc || !doc._doc) {
  2751. return;
  2752. }
  2753. seed = Object.keys(doc._doc).reduce(function(seed, path) {
  2754. return docReducer(doc._doc, seed, path);
  2755. }, seed);
  2756. if (doc instanceof Embedded) {
  2757. seed.push(doc);
  2758. }
  2759. });
  2760. } else if (isNested && val != null) {
  2761. for (const path of Object.keys(val)) {
  2762. docReducer(val, seed, path);
  2763. }
  2764. }
  2765. return seed;
  2766. }
  2767. const subDocs = [];
  2768. for (const path of Object.keys(this._doc)) {
  2769. docReducer(this, subDocs, path);
  2770. }
  2771. return subDocs;
  2772. };
  2773. /*!
  2774. * Runs queued functions
  2775. */
  2776. function applyQueue(doc) {
  2777. const q = doc.$__schema && doc.$__schema.callQueue;
  2778. if (!q.length) {
  2779. return;
  2780. }
  2781. for (const pair of q) {
  2782. if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') {
  2783. doc[pair[0]].apply(doc, pair[1]);
  2784. }
  2785. }
  2786. }
  2787. /*!
  2788. * ignore
  2789. */
  2790. Document.prototype.$__handleReject = function handleReject(err) {
  2791. // emit on the Model if listening
  2792. if (this.listeners('error').length) {
  2793. this.emit('error', err);
  2794. } else if (this.constructor.listeners && this.constructor.listeners('error').length) {
  2795. this.constructor.emit('error', err);
  2796. }
  2797. };
  2798. /**
  2799. * Internal helper for toObject() and toJSON() that doesn't manipulate options
  2800. *
  2801. * @api private
  2802. * @method $toObject
  2803. * @memberOf Document
  2804. * @instance
  2805. */
  2806. Document.prototype.$toObject = function(options, json) {
  2807. let defaultOptions = {
  2808. transform: true,
  2809. flattenDecimals: true
  2810. };
  2811. const path = json ? 'toJSON' : 'toObject';
  2812. const baseOptions = get(this, 'constructor.base.options.' + path, {});
  2813. const schemaOptions = get(this, '$__schema.options', {});
  2814. // merge base default options with Schema's set default options if available.
  2815. // `clone` is necessary here because `utils.options` directly modifies the second input.
  2816. defaultOptions = utils.options(defaultOptions, clone(baseOptions));
  2817. defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {}));
  2818. // If options do not exist or is not an object, set it to empty object
  2819. options = utils.isPOJO(options) ? clone(options) : {};
  2820. options._calledWithOptions = options._calledWithOptions || clone(options);
  2821. let _minimize;
  2822. if (options._calledWithOptions.minimize != null) {
  2823. _minimize = options.minimize;
  2824. } else if (defaultOptions.minimize != null) {
  2825. _minimize = defaultOptions.minimize;
  2826. } else {
  2827. _minimize = schemaOptions.minimize;
  2828. }
  2829. let flattenMaps;
  2830. if (options._calledWithOptions.flattenMaps != null) {
  2831. flattenMaps = options.flattenMaps;
  2832. } else if (defaultOptions.flattenMaps != null) {
  2833. flattenMaps = defaultOptions.flattenMaps;
  2834. } else {
  2835. flattenMaps = schemaOptions.flattenMaps;
  2836. }
  2837. // The original options that will be passed to `clone()`. Important because
  2838. // `clone()` will recursively call `$toObject()` on embedded docs, so we
  2839. // need the original options the user passed in, plus `_isNested` and
  2840. // `_parentOptions` for checking whether we need to depopulate.
  2841. const cloneOptions = Object.assign(utils.clone(options), {
  2842. _isNested: true,
  2843. json: json,
  2844. minimize: _minimize,
  2845. flattenMaps: flattenMaps
  2846. });
  2847. if (utils.hasUserDefinedProperty(options, 'getters')) {
  2848. cloneOptions.getters = options.getters;
  2849. }
  2850. if (utils.hasUserDefinedProperty(options, 'virtuals')) {
  2851. cloneOptions.virtuals = options.virtuals;
  2852. }
  2853. const depopulate = options.depopulate ||
  2854. get(options, '_parentOptions.depopulate', false);
  2855. // _isNested will only be true if this is not the top level document, we
  2856. // should never depopulate
  2857. if (depopulate && options._isNested && this.$__.wasPopulated) {
  2858. // populated paths that we set to a document
  2859. return clone(this._id, cloneOptions);
  2860. }
  2861. // merge default options with input options.
  2862. options = utils.options(defaultOptions, options);
  2863. options._isNested = true;
  2864. options.json = json;
  2865. options.minimize = _minimize;
  2866. cloneOptions._parentOptions = options;
  2867. cloneOptions._skipSingleNestedGetters = true;
  2868. const gettersOptions = Object.assign({}, cloneOptions);
  2869. gettersOptions._skipSingleNestedGetters = false;
  2870. // remember the root transform function
  2871. // to save it from being overwritten by sub-transform functions
  2872. const originalTransform = options.transform;
  2873. let ret = clone(this._doc, cloneOptions) || {};
  2874. if (options.getters) {
  2875. applyGetters(this, ret, gettersOptions);
  2876. if (options.minimize) {
  2877. ret = minimize(ret) || {};
  2878. }
  2879. }
  2880. if (options.virtuals || (options.getters && options.virtuals !== false)) {
  2881. applyVirtuals(this, ret, gettersOptions, options);
  2882. }
  2883. if (options.versionKey === false && this.$__schema.options.versionKey) {
  2884. delete ret[this.$__schema.options.versionKey];
  2885. }
  2886. let transform = options.transform;
  2887. // In the case where a subdocument has its own transform function, we need to
  2888. // check and see if the parent has a transform (options.transform) and if the
  2889. // child schema has a transform (this.schema.options.toObject) In this case,
  2890. // we need to adjust options.transform to be the child schema's transform and
  2891. // not the parent schema's
  2892. if (transform) {
  2893. applySchemaTypeTransforms(this, ret);
  2894. }
  2895. if (options.useProjection) {
  2896. omitDeselectedFields(this, ret);
  2897. }
  2898. if (transform === true || (schemaOptions.toObject && transform)) {
  2899. const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject;
  2900. if (opts) {
  2901. transform = (typeof options.transform === 'function' ? options.transform : opts.transform);
  2902. }
  2903. } else {
  2904. options.transform = originalTransform;
  2905. }
  2906. if (typeof transform === 'function') {
  2907. const xformed = transform(this, ret, options);
  2908. if (typeof xformed !== 'undefined') {
  2909. ret = xformed;
  2910. }
  2911. }
  2912. return ret;
  2913. };
  2914. /**
  2915. * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)).
  2916. *
  2917. * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage.
  2918. *
  2919. * ####Options:
  2920. *
  2921. * - `getters` apply all getters (path and virtual getters), defaults to false
  2922. * - `aliases` apply all aliases if `virtuals=true`, defaults to true
  2923. * - `virtuals` apply virtual getters (can override `getters` option), defaults to false
  2924. * - `minimize` remove empty objects, defaults to true
  2925. * - `transform` a transform function to apply to the resulting document before returning
  2926. * - `depopulate` depopulate any populated paths, replacing them with their original refs, defaults to false
  2927. * - `versionKey` whether to include the version key, defaults to true
  2928. * - `flattenMaps` convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false
  2929. * - `useProjection` set to `true` to omit fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema.
  2930. *
  2931. * ####Getters/Virtuals
  2932. *
  2933. * Example of only applying path getters
  2934. *
  2935. * doc.toObject({ getters: true, virtuals: false })
  2936. *
  2937. * Example of only applying virtual getters
  2938. *
  2939. * doc.toObject({ virtuals: true })
  2940. *
  2941. * Example of applying both path and virtual getters
  2942. *
  2943. * doc.toObject({ getters: true })
  2944. *
  2945. * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument.
  2946. *
  2947. * schema.set('toObject', { virtuals: true })
  2948. *
  2949. * ####Transform
  2950. *
  2951. * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function.
  2952. *
  2953. * Transform functions receive three arguments
  2954. *
  2955. * function (doc, ret, options) {}
  2956. *
  2957. * - `doc` The mongoose document which is being converted
  2958. * - `ret` The plain object representation which has been converted
  2959. * - `options` The options in use (either schema options or the options passed inline)
  2960. *
  2961. * ####Example
  2962. *
  2963. * // specify the transform schema option
  2964. * if (!schema.options.toObject) schema.options.toObject = {};
  2965. * schema.options.toObject.transform = function (doc, ret, options) {
  2966. * // remove the _id of every document before returning the result
  2967. * delete ret._id;
  2968. * return ret;
  2969. * }
  2970. *
  2971. * // without the transformation in the schema
  2972. * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  2973. *
  2974. * // with the transformation
  2975. * doc.toObject(); // { name: 'Wreck-it Ralph' }
  2976. *
  2977. * With transformations we can do a lot more than remove properties. We can even return completely new customized objects:
  2978. *
  2979. * if (!schema.options.toObject) schema.options.toObject = {};
  2980. * schema.options.toObject.transform = function (doc, ret, options) {
  2981. * return { movie: ret.name }
  2982. * }
  2983. *
  2984. * // without the transformation in the schema
  2985. * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  2986. *
  2987. * // with the transformation
  2988. * doc.toObject(); // { movie: 'Wreck-it Ralph' }
  2989. *
  2990. * _Note: if a transform function returns `undefined`, the return value will be ignored._
  2991. *
  2992. * Transformations may also be applied inline, overridding any transform set in the options:
  2993. *
  2994. * function xform (doc, ret, options) {
  2995. * return { inline: ret.name, custom: true }
  2996. * }
  2997. *
  2998. * // pass the transform as an inline option
  2999. * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
  3000. *
  3001. * If you want to skip transformations, use `transform: false`:
  3002. *
  3003. * schema.options.toObject.hide = '_id';
  3004. * schema.options.toObject.transform = function (doc, ret, options) {
  3005. * if (options.hide) {
  3006. * options.hide.split(' ').forEach(function (prop) {
  3007. * delete ret[prop];
  3008. * });
  3009. * }
  3010. * return ret;
  3011. * }
  3012. *
  3013. * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
  3014. * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
  3015. * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
  3016. * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }
  3017. *
  3018. * If you pass a transform in `toObject()` options, Mongoose will apply the transform
  3019. * to [subdocuments](/docs/subdocs.html) in addition to the top-level document.
  3020. * Similarly, `transform: false` skips transforms for all subdocuments.
  3021. * Note that this is behavior is different for transforms defined in the schema:
  3022. * if you define a transform in `schema.options.toObject.transform`, that transform
  3023. * will **not** apply to subdocuments.
  3024. *
  3025. * const memberSchema = new Schema({ name: String, email: String });
  3026. * const groupSchema = new Schema({ members: [memberSchema], name: String, email });
  3027. * const Group = mongoose.model('Group', groupSchema);
  3028. *
  3029. * const doc = new Group({
  3030. * name: 'Engineering',
  3031. * email: 'dev@mongoosejs.io',
  3032. * members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
  3033. * });
  3034. *
  3035. * // Removes `email` from both top-level document **and** array elements
  3036. * // { name: 'Engineering', members: [{ name: 'Val' }] }
  3037. * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });
  3038. *
  3039. * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions.
  3040. *
  3041. * See [schema options](/docs/guide.html#toObject) for some more details.
  3042. *
  3043. * _During save, no custom options are applied to the document before being sent to the database._
  3044. *
  3045. * @param {Object} [options]
  3046. * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals
  3047. * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals
  3048. * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`.
  3049. * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output
  3050. * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object
  3051. * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths.
  3052. * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output
  3053. * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`.
  3054. * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema.
  3055. * @return {Object} js object
  3056. * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html
  3057. * @api public
  3058. * @memberOf Document
  3059. * @instance
  3060. */
  3061. Document.prototype.toObject = function(options) {
  3062. return this.$toObject(options);
  3063. };
  3064. /*!
  3065. * Minimizes an object, removing undefined values and empty objects
  3066. *
  3067. * @param {Object} object to minimize
  3068. * @return {Object}
  3069. */
  3070. function minimize(obj) {
  3071. const keys = Object.keys(obj);
  3072. let i = keys.length;
  3073. let hasKeys;
  3074. let key;
  3075. let val;
  3076. while (i--) {
  3077. key = keys[i];
  3078. val = obj[key];
  3079. if (utils.isObject(val) && !Buffer.isBuffer(val)) {
  3080. obj[key] = minimize(val);
  3081. }
  3082. if (undefined === obj[key]) {
  3083. delete obj[key];
  3084. continue;
  3085. }
  3086. hasKeys = true;
  3087. }
  3088. return hasKeys
  3089. ? obj
  3090. : undefined;
  3091. }
  3092. /*!
  3093. * Applies virtuals properties to `json`.
  3094. */
  3095. function applyVirtuals(self, json, options, toObjectOptions) {
  3096. const schema = self.$__schema;
  3097. const paths = Object.keys(schema.virtuals);
  3098. let i = paths.length;
  3099. const numPaths = i;
  3100. let path;
  3101. let assignPath;
  3102. let cur = self._doc;
  3103. let v;
  3104. const aliases = get(toObjectOptions, 'aliases', true);
  3105. if (!cur) {
  3106. return json;
  3107. }
  3108. options = options || {};
  3109. for (i = 0; i < numPaths; ++i) {
  3110. path = paths[i];
  3111. // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })`
  3112. if (!aliases && schema.aliases.hasOwnProperty(path)) {
  3113. continue;
  3114. }
  3115. // We may be applying virtuals to a nested object, for example if calling
  3116. // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`,
  3117. // will be a trailing substring of the `path`.
  3118. assignPath = path;
  3119. if (options.path != null) {
  3120. if (!path.startsWith(options.path + '.')) {
  3121. continue;
  3122. }
  3123. assignPath = path.substr(options.path.length + 1);
  3124. }
  3125. const parts = assignPath.split('.');
  3126. v = clone(self.get(path), options);
  3127. if (v === void 0) {
  3128. continue;
  3129. }
  3130. const plen = parts.length;
  3131. cur = json;
  3132. for (let j = 0; j < plen - 1; ++j) {
  3133. cur[parts[j]] = cur[parts[j]] || {};
  3134. cur = cur[parts[j]];
  3135. }
  3136. cur[parts[plen - 1]] = v;
  3137. }
  3138. return json;
  3139. }
  3140. /*!
  3141. * Applies virtuals properties to `json`.
  3142. *
  3143. * @param {Document} self
  3144. * @param {Object} json
  3145. * @return {Object} `json`
  3146. */
  3147. function applyGetters(self, json, options) {
  3148. const schema = self.$__schema;
  3149. const paths = Object.keys(schema.paths);
  3150. let i = paths.length;
  3151. let path;
  3152. let cur = self._doc;
  3153. let v;
  3154. if (!cur) {
  3155. return json;
  3156. }
  3157. while (i--) {
  3158. path = paths[i];
  3159. const parts = path.split('.');
  3160. const plen = parts.length;
  3161. const last = plen - 1;
  3162. let branch = json;
  3163. let part;
  3164. cur = self._doc;
  3165. if (!self.$__isSelected(path)) {
  3166. continue;
  3167. }
  3168. for (let ii = 0; ii < plen; ++ii) {
  3169. part = parts[ii];
  3170. v = cur[part];
  3171. if (ii === last) {
  3172. const val = self.get(path);
  3173. branch[part] = clone(val, options);
  3174. } else if (v == null) {
  3175. if (part in cur) {
  3176. branch[part] = v;
  3177. }
  3178. break;
  3179. } else {
  3180. branch = branch[part] || (branch[part] = {});
  3181. }
  3182. cur = v;
  3183. }
  3184. }
  3185. return json;
  3186. }
  3187. /*!
  3188. * Applies schema type transforms to `json`.
  3189. *
  3190. * @param {Document} self
  3191. * @param {Object} json
  3192. * @return {Object} `json`
  3193. */
  3194. function applySchemaTypeTransforms(self, json) {
  3195. const schema = self.$__schema;
  3196. const paths = Object.keys(schema.paths || {});
  3197. const cur = self._doc;
  3198. if (!cur) {
  3199. return json;
  3200. }
  3201. for (const path of paths) {
  3202. const schematype = schema.paths[path];
  3203. if (typeof schematype.options.transform === 'function') {
  3204. const val = self.get(path);
  3205. const transformedValue = schematype.options.transform.call(self, val);
  3206. throwErrorIfPromise(path, transformedValue);
  3207. utils.setValue(path, transformedValue, json);
  3208. } else if (schematype.$embeddedSchemaType != null &&
  3209. typeof schematype.$embeddedSchemaType.options.transform === 'function') {
  3210. const vals = [].concat(self.get(path));
  3211. const transform = schematype.$embeddedSchemaType.options.transform;
  3212. for (let i = 0; i < vals.length; ++i) {
  3213. const transformedValue = transform.call(self, vals[i]);
  3214. vals[i] = transformedValue;
  3215. throwErrorIfPromise(path, transformedValue);
  3216. }
  3217. json[path] = vals;
  3218. }
  3219. }
  3220. return json;
  3221. }
  3222. function throwErrorIfPromise(path, transformedValue) {
  3223. if (isPromise(transformedValue)) {
  3224. throw new Error('`transform` function must be synchronous, but the transform on path `' + path + '` returned a promise.');
  3225. }
  3226. }
  3227. /*!
  3228. * ignore
  3229. */
  3230. function omitDeselectedFields(self, json) {
  3231. const schema = self.$__schema;
  3232. const paths = Object.keys(schema.paths || {});
  3233. const cur = self._doc;
  3234. if (!cur) {
  3235. return json;
  3236. }
  3237. let selected = self.$__.selected;
  3238. if (selected === void 0) {
  3239. selected = {};
  3240. queryhelpers.applyPaths(selected, schema);
  3241. }
  3242. if (selected == null || Object.keys(selected).length === 0) {
  3243. return json;
  3244. }
  3245. for (const path of paths) {
  3246. if (selected[path] != null && !selected[path]) {
  3247. delete json[path];
  3248. }
  3249. }
  3250. return json;
  3251. }
  3252. /**
  3253. * The return value of this method is used in calls to JSON.stringify(doc).
  3254. *
  3255. * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument.
  3256. *
  3257. * schema.set('toJSON', { virtuals: true })
  3258. *
  3259. * See [schema options](/docs/guide.html#toJSON) for details.
  3260. *
  3261. * @param {Object} options
  3262. * @return {Object}
  3263. * @see Document#toObject #document_Document-toObject
  3264. * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html
  3265. * @api public
  3266. * @memberOf Document
  3267. * @instance
  3268. */
  3269. Document.prototype.toJSON = function(options) {
  3270. return this.$toObject(options, true);
  3271. };
  3272. /**
  3273. * If this document is a subdocument or populated document, returns the document's
  3274. * parent. Returns `undefined` otherwise.
  3275. *
  3276. * @api public
  3277. * @method parent
  3278. * @memberOf Document
  3279. * @instance
  3280. */
  3281. Document.prototype.parent = function() {
  3282. return this.$__.parent;
  3283. };
  3284. /**
  3285. * Alias for `parent()`. If this document is a subdocument or populated
  3286. * document, returns the document's parent. Returns `undefined` otherwise.
  3287. *
  3288. * @api public
  3289. * @method $parent
  3290. * @memberOf Document
  3291. * @instance
  3292. */
  3293. Document.prototype.$parent = Document.prototype.parent;
  3294. /**
  3295. * Helper for console.log
  3296. *
  3297. * @api public
  3298. * @method inspect
  3299. * @memberOf Document
  3300. * @instance
  3301. */
  3302. Document.prototype.inspect = function(options) {
  3303. const isPOJO = utils.isPOJO(options);
  3304. let opts;
  3305. if (isPOJO) {
  3306. opts = options;
  3307. opts.minimize = false;
  3308. }
  3309. const ret = this.toObject(opts);
  3310. if (ret == null) {
  3311. // If `toObject()` returns null, `this` is still an object, so if `inspect()`
  3312. // prints out null this can cause some serious confusion. See gh-7942.
  3313. return 'MongooseDocument { ' + ret + ' }';
  3314. }
  3315. return ret;
  3316. };
  3317. if (inspect.custom) {
  3318. /*!
  3319. * Avoid Node deprecation warning DEP0079
  3320. */
  3321. Document.prototype[inspect.custom] = Document.prototype.inspect;
  3322. }
  3323. /**
  3324. * Helper for console.log
  3325. *
  3326. * @api public
  3327. * @method toString
  3328. * @memberOf Document
  3329. * @instance
  3330. */
  3331. Document.prototype.toString = function() {
  3332. const ret = this.inspect();
  3333. if (typeof ret === 'string') {
  3334. return ret;
  3335. }
  3336. return inspect(ret);
  3337. };
  3338. /**
  3339. * Returns true if this document is equal to another document.
  3340. *
  3341. * Documents are considered equal when they have matching `_id`s, unless neither
  3342. * document has an `_id`, in which case this function falls back to using
  3343. * `deepEqual()`.
  3344. *
  3345. * @param {Document} doc a document to compare
  3346. * @return {Boolean}
  3347. * @api public
  3348. * @memberOf Document
  3349. * @instance
  3350. */
  3351. Document.prototype.equals = function(doc) {
  3352. if (!doc) {
  3353. return false;
  3354. }
  3355. const tid = this.$__getValue('_id');
  3356. const docid = doc.$__ != null ? doc.$__getValue('_id') : doc;
  3357. if (!tid && !docid) {
  3358. return deepEqual(this, doc);
  3359. }
  3360. return tid && tid.equals
  3361. ? tid.equals(docid)
  3362. : tid === docid;
  3363. };
  3364. /**
  3365. * Populates document references, executing the `callback` when complete.
  3366. * If you want to use promises instead, use this function with
  3367. * [`execPopulate()`](#document_Document-execPopulate)
  3368. *
  3369. * ####Example:
  3370. *
  3371. * doc
  3372. * .populate('company')
  3373. * .populate({
  3374. * path: 'notes',
  3375. * match: /airline/,
  3376. * select: 'text',
  3377. * model: 'modelName'
  3378. * options: opts
  3379. * }, function (err, user) {
  3380. * assert(doc._id === user._id) // the document itself is passed
  3381. * })
  3382. *
  3383. * // summary
  3384. * doc.populate(path) // not executed
  3385. * doc.populate(options); // not executed
  3386. * doc.populate(path, callback) // executed
  3387. * doc.populate(options, callback); // executed
  3388. * doc.populate(callback); // executed
  3389. * doc.populate(options).execPopulate() // executed, returns promise
  3390. *
  3391. *
  3392. * ####NOTE:
  3393. *
  3394. * Population does not occur unless a `callback` is passed *or* you explicitly
  3395. * call `execPopulate()`.
  3396. * Passing the same path a second time will overwrite the previous path options.
  3397. * See [Model.populate()](#model_Model.populate) for explaination of options.
  3398. *
  3399. * @see Model.populate #model_Model.populate
  3400. * @see Document.execPopulate #document_Document-execPopulate
  3401. * @param {String|Object} [path] The path to populate or an options object
  3402. * @param {Function} [callback] When passed, population is invoked
  3403. * @api public
  3404. * @return {Document} this
  3405. * @memberOf Document
  3406. * @instance
  3407. */
  3408. Document.prototype.populate = function populate() {
  3409. if (arguments.length === 0) {
  3410. return this;
  3411. }
  3412. const pop = this.$__.populate || (this.$__.populate = {});
  3413. const args = utils.args(arguments);
  3414. let fn;
  3415. if (typeof args[args.length - 1] === 'function') {
  3416. fn = args.pop();
  3417. }
  3418. // allow `doc.populate(callback)`
  3419. if (args.length) {
  3420. // use hash to remove duplicate paths
  3421. const res = utils.populate.apply(null, args);
  3422. for (const populateOptions of res) {
  3423. pop[populateOptions.path] = populateOptions;
  3424. }
  3425. }
  3426. if (fn) {
  3427. const paths = utils.object.vals(pop);
  3428. this.$__.populate = undefined;
  3429. let topLevelModel = this.constructor;
  3430. if (this.$__isNested) {
  3431. topLevelModel = this.$__[scopeSymbol].constructor;
  3432. const nestedPath = this.$__.nestedPath;
  3433. paths.forEach(function(populateOptions) {
  3434. populateOptions.path = nestedPath + '.' + populateOptions.path;
  3435. });
  3436. }
  3437. // Use `$session()` by default if the document has an associated session
  3438. // See gh-6754
  3439. if (this.$session() != null) {
  3440. const session = this.$session();
  3441. paths.forEach(path => {
  3442. if (path.options == null) {
  3443. path.options = { session: session };
  3444. return;
  3445. }
  3446. if (!('session' in path.options)) {
  3447. path.options.session = session;
  3448. }
  3449. });
  3450. }
  3451. topLevelModel.populate(this, paths, fn);
  3452. }
  3453. return this;
  3454. };
  3455. /**
  3456. * Gets all populated documents associated with this document.
  3457. *
  3458. * @api public
  3459. * @return {Array<Document>} array of populated documents. Empty array if there are no populated documents associated with this document.
  3460. * @memberOf Document
  3461. * @instance
  3462. */
  3463. Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() {
  3464. let keys = [];
  3465. if (this.$__.populated != null) {
  3466. keys = keys.concat(Object.keys(this.$__.populated));
  3467. }
  3468. if (this.$$populatedVirtuals != null) {
  3469. keys = keys.concat(Object.keys(this.$$populatedVirtuals));
  3470. }
  3471. let result = [];
  3472. for (const key of keys) {
  3473. const value = this.get(key);
  3474. if (Array.isArray(value)) {
  3475. result = result.concat(value);
  3476. } else if (value instanceof Document) {
  3477. result.push(value);
  3478. }
  3479. }
  3480. return result;
  3481. };
  3482. /**
  3483. * Explicitly executes population and returns a promise. Useful for promises integration.
  3484. *
  3485. * ####Example:
  3486. *
  3487. * const promise = doc.
  3488. * populate('company').
  3489. * populate({
  3490. * path: 'notes',
  3491. * match: /airline/,
  3492. * select: 'text',
  3493. * model: 'modelName'
  3494. * options: opts
  3495. * }).
  3496. * execPopulate();
  3497. *
  3498. * // summary
  3499. * doc.execPopulate().then(resolve, reject);
  3500. *
  3501. * // you can also use doc.execPopulate(options) as a shorthand for
  3502. * // doc.populate(options).execPopulate()
  3503. *
  3504. *
  3505. * ####Example:
  3506. * const promise = doc.execPopulate({ path: 'company', select: 'employees' });
  3507. *
  3508. * // summary
  3509. * promise.then(resolve,reject);
  3510. *
  3511. * @see Document.populate #document_Document-populate
  3512. * @api public
  3513. * @param {Function} [callback] optional callback. If specified, a promise will **not** be returned
  3514. * @return {Promise} promise that resolves to the document when population is done
  3515. * @memberOf Document
  3516. * @instance
  3517. */
  3518. Document.prototype.execPopulate = function(callback) {
  3519. const isUsingShorthand = callback != null && typeof callback !== 'function';
  3520. if (isUsingShorthand) {
  3521. return this.populate.apply(this, arguments).execPopulate();
  3522. }
  3523. return promiseOrCallback(callback, cb => {
  3524. this.populate(cb);
  3525. }, this.constructor.events);
  3526. };
  3527. /**
  3528. * Gets _id(s) used during population of the given `path`.
  3529. *
  3530. * ####Example:
  3531. *
  3532. * Model.findOne().populate('author').exec(function (err, doc) {
  3533. * console.log(doc.author.name) // Dr.Seuss
  3534. * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
  3535. * })
  3536. *
  3537. * If the path was not populated, returns `undefined`.
  3538. *
  3539. * @param {String} path
  3540. * @return {Array|ObjectId|Number|Buffer|String|undefined}
  3541. * @memberOf Document
  3542. * @instance
  3543. * @api public
  3544. */
  3545. Document.prototype.populated = function(path, val, options) {
  3546. // val and options are internal
  3547. if (val == null || val === true) {
  3548. if (!this.$__.populated) {
  3549. return undefined;
  3550. }
  3551. // Map paths can be populated with either `path.$*` or just `path`
  3552. const _path = path.endsWith('.$*') ? path.replace(/\.\$\*$/, '') : path;
  3553. const v = this.$__.populated[_path];
  3554. if (v) {
  3555. return val === true ? v : v.value;
  3556. }
  3557. return undefined;
  3558. }
  3559. this.$__.populated || (this.$__.populated = {});
  3560. this.$__.populated[path] = { value: val, options: options };
  3561. // If this was a nested populate, make sure each populated doc knows
  3562. // about its populated children (gh-7685)
  3563. const pieces = path.split('.');
  3564. for (let i = 0; i < pieces.length - 1; ++i) {
  3565. const subpath = pieces.slice(0, i + 1).join('.');
  3566. const subdoc = this.get(subpath);
  3567. if (subdoc != null && subdoc.$__ != null && this.populated(subpath)) {
  3568. const rest = pieces.slice(i + 1).join('.');
  3569. subdoc.populated(rest, val, options);
  3570. // No need to continue because the above recursion should take care of
  3571. // marking the rest of the docs as populated
  3572. break;
  3573. }
  3574. }
  3575. return val;
  3576. };
  3577. /**
  3578. * Takes a populated field and returns it to its unpopulated state.
  3579. *
  3580. * ####Example:
  3581. *
  3582. * Model.findOne().populate('author').exec(function (err, doc) {
  3583. * console.log(doc.author.name); // Dr.Seuss
  3584. * console.log(doc.depopulate('author'));
  3585. * console.log(doc.author); // '5144cf8050f071d979c118a7'
  3586. * })
  3587. *
  3588. * If the path was not populated, this is a no-op.
  3589. *
  3590. * @param {String} path
  3591. * @return {Document} this
  3592. * @see Document.populate #document_Document-populate
  3593. * @api public
  3594. * @memberOf Document
  3595. * @instance
  3596. */
  3597. Document.prototype.depopulate = function(path) {
  3598. if (typeof path === 'string') {
  3599. path = path.split(' ');
  3600. }
  3601. let populatedIds;
  3602. const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : [];
  3603. const populated = get(this, '$__.populated', {});
  3604. if (arguments.length === 0) {
  3605. // Depopulate all
  3606. for (const virtualKey of virtualKeys) {
  3607. delete this.$$populatedVirtuals[virtualKey];
  3608. delete this._doc[virtualKey];
  3609. delete populated[virtualKey];
  3610. }
  3611. const keys = Object.keys(populated);
  3612. for (const key of keys) {
  3613. populatedIds = this.populated(key);
  3614. if (!populatedIds) {
  3615. continue;
  3616. }
  3617. delete populated[key];
  3618. this.$set(key, populatedIds);
  3619. }
  3620. return this;
  3621. }
  3622. for (const singlePath of path) {
  3623. populatedIds = this.populated(singlePath);
  3624. delete populated[singlePath];
  3625. if (virtualKeys.indexOf(singlePath) !== -1) {
  3626. delete this.$$populatedVirtuals[singlePath];
  3627. delete this._doc[singlePath];
  3628. } else if (populatedIds) {
  3629. this.$set(singlePath, populatedIds);
  3630. }
  3631. }
  3632. return this;
  3633. };
  3634. /**
  3635. * Returns the full path to this document.
  3636. *
  3637. * @param {String} [path]
  3638. * @return {String}
  3639. * @api private
  3640. * @method $__fullPath
  3641. * @memberOf Document
  3642. * @instance
  3643. */
  3644. Document.prototype.$__fullPath = function(path) {
  3645. // overridden in SubDocuments
  3646. return path || '';
  3647. };
  3648. /**
  3649. * Returns the changes that happened to the document
  3650. * in the format that will be sent to MongoDB.
  3651. *
  3652. * #### Example:
  3653. *
  3654. * const userSchema = new Schema({
  3655. * name: String,
  3656. * age: Number,
  3657. * country: String
  3658. * });
  3659. * const User = mongoose.model('User', userSchema);
  3660. * const user = await User.create({
  3661. * name: 'Hafez',
  3662. * age: 25,
  3663. * country: 'Egypt'
  3664. * });
  3665. *
  3666. * // returns an empty object, no changes happened yet
  3667. * user.getChanges(); // { }
  3668. *
  3669. * user.country = undefined;
  3670. * user.age = 26;
  3671. *
  3672. * user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
  3673. *
  3674. * await user.save();
  3675. *
  3676. * user.getChanges(); // { }
  3677. *
  3678. * Modifying the object that `getChanges()` returns does not affect the document's
  3679. * change tracking state. Even if you `delete user.getChanges().$set`, Mongoose
  3680. * will still send a `$set` to the server.
  3681. *
  3682. * @return {Object}
  3683. * @api public
  3684. * @method getChanges
  3685. * @memberOf Document
  3686. * @instance
  3687. */
  3688. Document.prototype.getChanges = function() {
  3689. const delta = this.$__delta();
  3690. const changes = delta ? delta[1] : {};
  3691. return changes;
  3692. };
  3693. /*!
  3694. * Module exports.
  3695. */
  3696. Document.ValidationError = ValidationError;
  3697. module.exports = exports = Document;