document.js 118 KB

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