document.js 89 KB

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