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

document.js 89KB

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