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

document.js 90KB

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