document.js 83 KB

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