document.js 128 KB

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