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

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