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 83KB

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