document.js 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615
  1. /*!
  2. * Module dependencies.
  3. */
  4. var EventEmitter = require('events').EventEmitter;
  5. var MongooseError = require('./error');
  6. var MixedSchema = require('./schema/mixed');
  7. var Schema = require('./schema');
  8. var ObjectExpectedError = require('./error/objectExpected');
  9. var StrictModeError = require('./error/strict');
  10. var ValidatorError = require('./schematype').ValidatorError;
  11. var VersionError = require('./error').VersionError;
  12. var utils = require('./utils');
  13. var clone = utils.clone;
  14. var isMongooseObject = utils.isMongooseObject;
  15. var inspect = require('util').inspect;
  16. var ValidationError = MongooseError.ValidationError;
  17. var InternalCache = require('./internal');
  18. var deepEqual = utils.deepEqual;
  19. var hooks = require('hooks-fixed');
  20. var PromiseProvider = require('./promise_provider');
  21. var DocumentArray;
  22. var MongooseArray;
  23. var Embedded;
  24. var flatten = require('./services/common').flatten;
  25. var mpath = require('mpath');
  26. /**
  27. * Document constructor.
  28. *
  29. * @param {Object} obj the values to set
  30. * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
  31. * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
  32. * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
  33. * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.
  34. * @event `save`: Emitted when the document is successfully saved
  35. * @api private
  36. */
  37. function Document(obj, fields, skipId) {
  38. this.$__ = new InternalCache;
  39. this.$__.emitter = new EventEmitter();
  40. this.isNew = true;
  41. this.errors = undefined;
  42. var schema = this.schema;
  43. if (typeof fields === 'boolean') {
  44. this.$__.strictMode = fields;
  45. fields = undefined;
  46. } else {
  47. this.$__.strictMode = schema.options && schema.options.strict;
  48. this.$__.selected = fields;
  49. }
  50. var required = schema.requiredPaths(true);
  51. for (var i = 0; i < required.length; ++i) {
  52. this.$__.activePaths.require(required[i]);
  53. }
  54. this.$__.emitter.setMaxListeners(0);
  55. this._doc = this.$__buildDoc(obj, fields, skipId);
  56. if (obj) {
  57. if (obj instanceof Document) {
  58. this.isNew = obj.isNew;
  59. }
  60. this.set(obj, undefined, true);
  61. }
  62. if (!schema.options.strict && obj) {
  63. var _this = this,
  64. keys = Object.keys(this._doc);
  65. keys.forEach(function(key) {
  66. if (!(key in schema.tree)) {
  67. defineKey(key, null, _this);
  68. }
  69. });
  70. }
  71. this.$__registerHooksFromSchema();
  72. }
  73. /*!
  74. * Document exposes the NodeJS event emitter API, so you can use
  75. * `on`, `once`, etc.
  76. */
  77. utils.each(
  78. ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
  79. 'removeAllListeners', 'addListener'],
  80. function(emitterFn) {
  81. Document.prototype[emitterFn] = function() {
  82. return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments);
  83. };
  84. });
  85. Document.prototype.constructor = Document;
  86. /**
  87. * The documents schema.
  88. *
  89. * @api public
  90. * @property schema
  91. */
  92. Document.prototype.schema;
  93. /**
  94. * Boolean flag specifying if the document is new.
  95. *
  96. * @api public
  97. * @property isNew
  98. */
  99. Document.prototype.isNew;
  100. /**
  101. * The string version of this documents _id.
  102. *
  103. * ####Note:
  104. *
  105. * 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.
  106. *
  107. * new Schema({ name: String }, { id: false });
  108. *
  109. * @api public
  110. * @see Schema options /docs/guide.html#options
  111. * @property id
  112. */
  113. Document.prototype.id;
  114. /**
  115. * Hash containing current validation errors.
  116. *
  117. * @api public
  118. * @property errors
  119. */
  120. Document.prototype.errors;
  121. /**
  122. * Builds the default doc structure
  123. *
  124. * @param {Object} obj
  125. * @param {Object} [fields]
  126. * @param {Boolean} [skipId]
  127. * @return {Object}
  128. * @api private
  129. * @method $__buildDoc
  130. * @memberOf Document
  131. */
  132. Document.prototype.$__buildDoc = function(obj, fields, skipId) {
  133. var doc = {};
  134. var exclude = null;
  135. var keys;
  136. var ki;
  137. var _this = this;
  138. // determine if this doc is a result of a query with
  139. // excluded fields
  140. if (fields && utils.getFunctionName(fields.constructor) === 'Object') {
  141. keys = Object.keys(fields);
  142. ki = keys.length;
  143. if (ki === 1 && keys[0] === '_id') {
  144. exclude = !!fields[keys[ki]];
  145. } else {
  146. while (ki--) {
  147. if (keys[ki] !== '_id' &&
  148. (!fields[keys[ki]] || typeof fields[keys[ki]] !== 'object')) {
  149. exclude = !fields[keys[ki]];
  150. break;
  151. }
  152. }
  153. }
  154. }
  155. var paths = Object.keys(this.schema.paths);
  156. var plen = paths.length;
  157. var ii = 0;
  158. var hasIncludedChildren = {};
  159. if (exclude === false && fields) {
  160. keys = Object.keys(fields);
  161. for (var j = 0; j < keys.length; ++j) {
  162. var parts = keys[j].split('.');
  163. var c = [];
  164. for (var k = 0; k < parts.length; ++k) {
  165. c.push(parts[k]);
  166. hasIncludedChildren[c.join('.')] = 1;
  167. }
  168. }
  169. }
  170. for (; ii < plen; ++ii) {
  171. var p = paths[ii];
  172. if (p === '_id') {
  173. if (skipId) {
  174. continue;
  175. }
  176. if (obj && '_id' in obj) {
  177. continue;
  178. }
  179. }
  180. var type = this.schema.paths[p];
  181. var path = p.split('.');
  182. var len = path.length;
  183. var last = len - 1;
  184. var curPath = '';
  185. var doc_ = doc;
  186. var i = 0;
  187. var included = false;
  188. for (; i < len; ++i) {
  189. var piece = path[i],
  190. def;
  191. curPath += (!curPath.length ? '' : '.') + piece;
  192. // support excluding intermediary levels
  193. if (exclude === true) {
  194. if (curPath in fields) {
  195. break;
  196. }
  197. } else if (exclude === false && fields && !included) {
  198. if (curPath in fields) {
  199. included = true;
  200. } else if (!hasIncludedChildren[curPath]) {
  201. break;
  202. }
  203. }
  204. if (i === last) {
  205. if (fields && exclude !== null) {
  206. if (exclude === true) {
  207. // apply defaults to all non-excluded fields
  208. if (p in fields) {
  209. continue;
  210. }
  211. def = type.getDefault(_this, false);
  212. if (typeof def !== 'undefined') {
  213. doc_[piece] = def;
  214. _this.$__.activePaths.default(p);
  215. }
  216. } else if (included) {
  217. // selected field
  218. def = type.getDefault(_this, false);
  219. if (typeof def !== 'undefined') {
  220. doc_[piece] = def;
  221. _this.$__.activePaths.default(p);
  222. }
  223. }
  224. } else {
  225. def = type.getDefault(_this, false);
  226. if (typeof def !== 'undefined') {
  227. doc_[piece] = def;
  228. _this.$__.activePaths.default(p);
  229. }
  230. }
  231. } else {
  232. doc_ = doc_[piece] || (doc_[piece] = {});
  233. }
  234. }
  235. }
  236. return doc;
  237. };
  238. /**
  239. * Initializes the document without setters or marking anything modified.
  240. *
  241. * Called internally after a document is returned from mongodb.
  242. *
  243. * @param {Object} doc document returned by mongo
  244. * @param {Function} fn callback
  245. * @api public
  246. */
  247. Document.prototype.init = function(doc, opts, fn) {
  248. // do not prefix this method with $__ since its
  249. // used by public hooks
  250. if (typeof opts === 'function') {
  251. fn = opts;
  252. opts = null;
  253. }
  254. this.isNew = false;
  255. // handle docs with populated paths
  256. // If doc._id is not null or undefined
  257. if (doc._id !== null && doc._id !== undefined &&
  258. opts && opts.populated && opts.populated.length) {
  259. var id = String(doc._id);
  260. for (var i = 0; i < opts.populated.length; ++i) {
  261. var item = opts.populated[i];
  262. if (item.isVirtual) {
  263. this.populated(item.path, utils.getValue(item.path, doc), item);
  264. } else {
  265. this.populated(item.path, item._docs[id], item);
  266. }
  267. }
  268. }
  269. init(this, doc, this._doc);
  270. this.$__storeShard();
  271. this.emit('init', this);
  272. if (fn) {
  273. fn(null);
  274. }
  275. return this;
  276. };
  277. /*!
  278. * Init helper.
  279. *
  280. * @param {Object} self document instance
  281. * @param {Object} obj raw mongodb doc
  282. * @param {Object} doc object we are initializing
  283. * @api private
  284. */
  285. function init(self, obj, doc, prefix) {
  286. prefix = prefix || '';
  287. var keys = Object.keys(obj);
  288. var len = keys.length;
  289. var schema;
  290. var path;
  291. var i;
  292. var index = 0;
  293. if (self.schema.options.retainKeyOrder) {
  294. while (index < len) {
  295. _init(index++);
  296. }
  297. } else {
  298. while (len--) {
  299. _init(len);
  300. }
  301. }
  302. function _init(index) {
  303. i = keys[index];
  304. path = prefix + i;
  305. schema = self.schema.path(path);
  306. if (!schema && utils.isObject(obj[i]) &&
  307. (!obj[i].constructor || utils.getFunctionName(obj[i].constructor) === 'Object')) {
  308. // assume nested object
  309. if (!doc[i]) {
  310. doc[i] = {};
  311. }
  312. init(self, obj[i], doc[i], path + '.');
  313. } else {
  314. if (obj[i] === null) {
  315. doc[i] = null;
  316. } else if (obj[i] !== undefined) {
  317. if (schema) {
  318. try {
  319. doc[i] = schema.cast(obj[i], self, true);
  320. } catch (e) {
  321. self.invalidate(e.path, new ValidatorError({
  322. path: e.path,
  323. message: e.message,
  324. type: 'cast',
  325. value: e.value
  326. }));
  327. }
  328. } else {
  329. doc[i] = obj[i];
  330. }
  331. }
  332. // mark as hydrated
  333. if (!self.isModified(path)) {
  334. self.$__.activePaths.init(path);
  335. }
  336. }
  337. }
  338. }
  339. /**
  340. * Stores the current values of the shard keys.
  341. *
  342. * ####Note:
  343. *
  344. * _Shard key values do not / are not allowed to change._
  345. *
  346. * @api private
  347. * @method $__storeShard
  348. * @memberOf Document
  349. */
  350. Document.prototype.$__storeShard = function() {
  351. // backwards compat
  352. var key = this.schema.options.shardKey || this.schema.options.shardkey;
  353. if (!(key && utils.getFunctionName(key.constructor) === 'Object')) {
  354. return;
  355. }
  356. var orig = this.$__.shardval = {},
  357. paths = Object.keys(key),
  358. len = paths.length,
  359. val;
  360. for (var i = 0; i < len; ++i) {
  361. val = this.getValue(paths[i]);
  362. if (isMongooseObject(val)) {
  363. orig[paths[i]] = val.toObject({depopulate: true, _isNested: true});
  364. } else if (val !== null && val !== undefined && val.valueOf &&
  365. // Explicitly don't take value of dates
  366. (!val.constructor || utils.getFunctionName(val.constructor) !== 'Date')) {
  367. orig[paths[i]] = val.valueOf();
  368. } else {
  369. orig[paths[i]] = val;
  370. }
  371. }
  372. };
  373. /*!
  374. * Set up middleware support
  375. */
  376. for (var k in hooks) {
  377. if (k === 'pre' || k === 'post') {
  378. Document.prototype['$' + k] = Document['$' + k] = hooks[k];
  379. } else {
  380. Document.prototype[k] = Document[k] = hooks[k];
  381. }
  382. }
  383. /**
  384. * Sends an update command with this document `_id` as the query selector.
  385. *
  386. * ####Example:
  387. *
  388. * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
  389. *
  390. * ####Valid options:
  391. *
  392. * - same as in [Model.update](#model_Model.update)
  393. *
  394. * @see Model.update #model_Model.update
  395. * @param {Object} doc
  396. * @param {Object} options
  397. * @param {Function} callback
  398. * @return {Query}
  399. * @api public
  400. */
  401. Document.prototype.update = function update() {
  402. var args = utils.args(arguments);
  403. args.unshift({_id: this._id});
  404. return this.constructor.update.apply(this.constructor, args);
  405. };
  406. /**
  407. * Sets the value of a path, or many paths.
  408. *
  409. * ####Example:
  410. *
  411. * // path, value
  412. * doc.set(path, value)
  413. *
  414. * // object
  415. * doc.set({
  416. * path : value
  417. * , path2 : {
  418. * path : value
  419. * }
  420. * })
  421. *
  422. * // on-the-fly cast to number
  423. * doc.set(path, value, Number)
  424. *
  425. * // on-the-fly cast to string
  426. * doc.set(path, value, String)
  427. *
  428. * // changing strict mode behavior
  429. * doc.set(path, value, { strict: false });
  430. *
  431. * @param {String|Object} path path or object of key/vals to set
  432. * @param {Any} val the value to set
  433. * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes
  434. * @param {Object} [options] optionally specify options that modify the behavior of the set
  435. * @api public
  436. */
  437. Document.prototype.set = function(path, val, type, options) {
  438. if (type && utils.getFunctionName(type.constructor) === 'Object') {
  439. options = type;
  440. type = undefined;
  441. }
  442. var merge = options && options.merge,
  443. adhoc = type && type !== true,
  444. constructing = type === true,
  445. adhocs;
  446. var strict = options && 'strict' in options
  447. ? options.strict
  448. : this.$__.strictMode;
  449. if (adhoc) {
  450. adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
  451. adhocs[path] = Schema.interpretAsType(path, type, this.schema.options);
  452. }
  453. if (typeof path !== 'string') {
  454. // new Document({ key: val })
  455. if (path === null || path === void 0) {
  456. var _ = path;
  457. path = val;
  458. val = _;
  459. } else {
  460. var prefix = val
  461. ? val + '.'
  462. : '';
  463. if (path instanceof Document) {
  464. if (path.$__isNested) {
  465. path = path.toObject();
  466. } else {
  467. path = path._doc;
  468. }
  469. }
  470. var keys = Object.keys(path);
  471. var len = keys.length;
  472. var i = 0;
  473. var pathtype;
  474. var key;
  475. if (len === 0 && !this.schema.options.minimize) {
  476. if (val) {
  477. this.set(val, {});
  478. }
  479. return this;
  480. }
  481. if (this.schema.options.retainKeyOrder) {
  482. while (i < len) {
  483. _handleIndex.call(this, i++);
  484. }
  485. } else {
  486. while (len--) {
  487. _handleIndex.call(this, len);
  488. }
  489. }
  490. return this;
  491. }
  492. }
  493. function _handleIndex(i) {
  494. key = keys[i];
  495. var pathName = prefix + key;
  496. pathtype = this.schema.pathType(pathName);
  497. if (path[key] !== null
  498. && path[key] !== void 0
  499. // need to know if plain object - no Buffer, ObjectId, ref, etc
  500. && utils.isObject(path[key])
  501. && (!path[key].constructor || utils.getFunctionName(path[key].constructor) === 'Object')
  502. && pathtype !== 'virtual'
  503. && pathtype !== 'real'
  504. && !(this.$__path(pathName) instanceof MixedSchema)
  505. && !(this.schema.paths[pathName] &&
  506. this.schema.paths[pathName].options &&
  507. this.schema.paths[pathName].options.ref)) {
  508. this.set(path[key], prefix + key, constructing);
  509. } else if (strict) {
  510. // Don't overwrite defaults with undefined keys (gh-3981)
  511. if (constructing && path[key] === void 0 &&
  512. this.get(key) !== void 0) {
  513. return;
  514. }
  515. if (pathtype === 'real' || pathtype === 'virtual') {
  516. // Check for setting single embedded schema to document (gh-3535)
  517. if (this.schema.paths[pathName] &&
  518. this.schema.paths[pathName].$isSingleNested &&
  519. path[key] instanceof Document) {
  520. path[key] = path[key].toObject({virtuals: false});
  521. }
  522. this.set(prefix + key, path[key], constructing);
  523. } else if (pathtype === 'nested' && path[key] instanceof Document) {
  524. this.set(prefix + key,
  525. path[key].toObject({transform: false}), constructing);
  526. } else if (strict === 'throw') {
  527. if (pathtype === 'nested') {
  528. throw new ObjectExpectedError(key, path[key]);
  529. } else {
  530. throw new StrictModeError(key);
  531. }
  532. }
  533. } else if (path[key] !== void 0) {
  534. this.set(prefix + key, path[key], constructing);
  535. }
  536. }
  537. // ensure _strict is honored for obj props
  538. // docschema = new Schema({ path: { nest: 'string' }})
  539. // doc.set('path', obj);
  540. var pathType = this.schema.pathType(path);
  541. if (pathType === 'nested' && val) {
  542. if (utils.isObject(val) &&
  543. (!val.constructor || utils.getFunctionName(val.constructor) === 'Object')) {
  544. if (!merge) {
  545. this.setValue(path, null);
  546. cleanModifiedSubpaths(this, path);
  547. }
  548. if (Object.keys(val).length === 0) {
  549. this.setValue(path, {});
  550. this.markModified(path);
  551. cleanModifiedSubpaths(this, path);
  552. } else {
  553. this.set(val, path, constructing);
  554. }
  555. return this;
  556. }
  557. this.invalidate(path, new MongooseError.CastError('Object', val, path));
  558. return this;
  559. }
  560. var schema;
  561. var parts = path.split('.');
  562. if (pathType === 'adhocOrUndefined' && strict) {
  563. // check for roots that are Mixed types
  564. var mixed;
  565. for (i = 0; i < parts.length; ++i) {
  566. var subpath = parts.slice(0, i + 1).join('.');
  567. schema = this.schema.path(subpath);
  568. if (schema instanceof MixedSchema) {
  569. // allow changes to sub paths of mixed types
  570. mixed = true;
  571. break;
  572. }
  573. // If path is underneath a virtual, bypass everything and just set it.
  574. if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') {
  575. mpath.set(path, val, this);
  576. return this;
  577. }
  578. }
  579. if (!mixed) {
  580. if (strict === 'throw') {
  581. throw new StrictModeError(path);
  582. }
  583. return this;
  584. }
  585. } else if (pathType === 'virtual') {
  586. schema = this.schema.virtualpath(path);
  587. schema.applySetters(val, this);
  588. return this;
  589. } else {
  590. schema = this.$__path(path);
  591. }
  592. var pathToMark;
  593. // When using the $set operator the path to the field must already exist.
  594. // Else mongodb throws: "LEFT_SUBFIELD only supports Object"
  595. if (parts.length <= 1) {
  596. pathToMark = path;
  597. } else {
  598. for (i = 0; i < parts.length; ++i) {
  599. subpath = parts.slice(0, i + 1).join('.');
  600. if (this.isDirectModified(subpath) // earlier prefixes that are already
  601. // marked as dirty have precedence
  602. || this.get(subpath) === null) {
  603. pathToMark = subpath;
  604. break;
  605. }
  606. }
  607. if (!pathToMark) {
  608. pathToMark = path;
  609. }
  610. }
  611. // if this doc is being constructed we should not trigger getters
  612. var priorVal = constructing
  613. ? undefined
  614. : this.getValue(path);
  615. if (!schema) {
  616. this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
  617. return this;
  618. }
  619. var shouldSet = true;
  620. try {
  621. // If the user is trying to set a ref path to a document with
  622. // the correct model name, treat it as populated
  623. var didPopulate = false;
  624. if (schema.options &&
  625. schema.options.ref &&
  626. val instanceof Document &&
  627. schema.options.ref === val.constructor.modelName) {
  628. if (this.ownerDocument) {
  629. this.ownerDocument().populated(this.$__fullPath(path),
  630. val._id, {model: val.constructor});
  631. } else {
  632. this.populated(path, val._id, {model: val.constructor});
  633. }
  634. didPopulate = true;
  635. }
  636. var popOpts;
  637. if (schema.options &&
  638. Array.isArray(schema.options.type) &&
  639. schema.options.type.length &&
  640. schema.options.type[0].ref &&
  641. Array.isArray(val) &&
  642. val.length > 0 &&
  643. val[0] instanceof Document &&
  644. val[0].constructor.modelName &&
  645. schema.options.type[0].ref === val[0].constructor.modelName) {
  646. if (this.ownerDocument) {
  647. popOpts = { model: val[0].constructor };
  648. this.ownerDocument().populated(this.$__fullPath(path),
  649. val.map(function(v) { return v._id; }), popOpts);
  650. } else {
  651. popOpts = { model: val[0].constructor };
  652. this.populated(path, val.map(function(v) { return v._id; }), popOpts);
  653. }
  654. didPopulate = true;
  655. }
  656. val = schema.applySetters(val, this, false, priorVal);
  657. if (!didPopulate && this.$__.populated) {
  658. delete this.$__.populated[path];
  659. }
  660. this.$markValid(path);
  661. } catch (e) {
  662. this.invalidate(path,
  663. new MongooseError.CastError(schema.instance, val, path, e));
  664. shouldSet = false;
  665. }
  666. if (shouldSet) {
  667. this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
  668. }
  669. if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) {
  670. cleanModifiedSubpaths(this, path);
  671. }
  672. return this;
  673. };
  674. /*!
  675. * ignore
  676. */
  677. function cleanModifiedSubpaths(doc, path) {
  678. var _modifiedPaths = Object.keys(doc.$__.activePaths.states.modify);
  679. var _numModifiedPaths = _modifiedPaths.length;
  680. for (var j = 0; j < _numModifiedPaths; ++j) {
  681. if (_modifiedPaths[j].indexOf(path + '.') === 0) {
  682. delete doc.$__.activePaths.states.modify[_modifiedPaths[j]];
  683. }
  684. }
  685. }
  686. /**
  687. * Determine if we should mark this change as modified.
  688. *
  689. * @return {Boolean}
  690. * @api private
  691. * @method $__shouldModify
  692. * @memberOf Document
  693. */
  694. Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
  695. if (this.isNew) {
  696. return true;
  697. }
  698. if (undefined === val && !this.isSelected(path)) {
  699. // when a path is not selected in a query, its initial
  700. // value will be undefined.
  701. return true;
  702. }
  703. if (undefined === val && path in this.$__.activePaths.states.default) {
  704. // we're just unsetting the default value which was never saved
  705. return false;
  706. }
  707. // gh-3992: if setting a populated field to a doc, don't mark modified
  708. // if they have the same _id
  709. if (this.populated(path) &&
  710. val instanceof Document &&
  711. deepEqual(val._id, priorVal)) {
  712. return false;
  713. }
  714. if (!deepEqual(val, priorVal || this.get(path))) {
  715. return true;
  716. }
  717. if (!constructing &&
  718. val !== null &&
  719. val !== undefined &&
  720. path in this.$__.activePaths.states.default &&
  721. deepEqual(val, schema.getDefault(this, constructing))) {
  722. // a path with a default was $unset on the server
  723. // and the user is setting it to the same value again
  724. return true;
  725. }
  726. return false;
  727. };
  728. /**
  729. * Handles the actual setting of the value and marking the path modified if appropriate.
  730. *
  731. * @api private
  732. * @method $__set
  733. * @memberOf Document
  734. */
  735. Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) {
  736. Embedded = Embedded || require('./types/embedded');
  737. var shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts,
  738. schema, val, priorVal);
  739. var _this = this;
  740. if (shouldModify) {
  741. this.markModified(pathToMark, val);
  742. // handle directly setting arrays (gh-1126)
  743. MongooseArray || (MongooseArray = require('./types/array'));
  744. if (val && val.isMongooseArray) {
  745. val._registerAtomic('$set', val);
  746. // Small hack for gh-1638: if we're overwriting the entire array, ignore
  747. // paths that were modified before the array overwrite
  748. this.$__.activePaths.forEach(function(modifiedPath) {
  749. if (modifiedPath.indexOf(path + '.') === 0) {
  750. _this.$__.activePaths.ignore(modifiedPath);
  751. }
  752. });
  753. }
  754. }
  755. var obj = this._doc;
  756. var i = 0;
  757. var l = parts.length;
  758. var cur = '';
  759. for (; i < l; i++) {
  760. var next = i + 1;
  761. var last = next === l;
  762. cur += (cur ? '.' + parts[i] : parts[i]);
  763. if (last) {
  764. obj[parts[i]] = val;
  765. } else {
  766. if (obj[parts[i]] && utils.getFunctionName(obj[parts[i]].constructor) === 'Object') {
  767. obj = obj[parts[i]];
  768. } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) {
  769. obj = obj[parts[i]];
  770. } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) {
  771. obj = obj[parts[i]];
  772. } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
  773. obj = obj[parts[i]];
  774. } else {
  775. this.set(cur, {});
  776. obj = obj[parts[i]];
  777. }
  778. }
  779. }
  780. };
  781. /**
  782. * Gets a raw value from a path (no getters)
  783. *
  784. * @param {String} path
  785. * @api private
  786. */
  787. Document.prototype.getValue = function(path) {
  788. return utils.getValue(path, this._doc);
  789. };
  790. /**
  791. * Sets a raw value for a path (no casting, setters, transformations)
  792. *
  793. * @param {String} path
  794. * @param {Object} value
  795. * @api private
  796. */
  797. Document.prototype.setValue = function(path, val) {
  798. utils.setValue(path, val, this._doc);
  799. return this;
  800. };
  801. /**
  802. * Returns the value of a path.
  803. *
  804. * ####Example
  805. *
  806. * // path
  807. * doc.get('age') // 47
  808. *
  809. * // dynamic casting to a string
  810. * doc.get('age', String) // "47"
  811. *
  812. * @param {String} path
  813. * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes
  814. * @api public
  815. */
  816. Document.prototype.get = function(path, type) {
  817. var adhoc;
  818. if (type) {
  819. adhoc = Schema.interpretAsType(path, type, this.schema.options);
  820. }
  821. var schema = this.$__path(path) || this.schema.virtualpath(path),
  822. pieces = path.split('.'),
  823. obj = this._doc;
  824. for (var i = 0, l = pieces.length; i < l; i++) {
  825. obj = obj === null || obj === void 0
  826. ? undefined
  827. : obj[pieces[i]];
  828. }
  829. if (adhoc) {
  830. obj = adhoc.cast(obj);
  831. }
  832. // Check if this path is populated - don't apply getters if it is,
  833. // because otherwise its a nested object. See gh-3357
  834. if (schema && !this.populated(path)) {
  835. obj = schema.applyGetters(obj, this);
  836. }
  837. return obj;
  838. };
  839. /**
  840. * Returns the schematype for the given `path`.
  841. *
  842. * @param {String} path
  843. * @api private
  844. * @method $__path
  845. * @memberOf Document
  846. */
  847. Document.prototype.$__path = function(path) {
  848. var adhocs = this.$__.adhocPaths,
  849. adhocType = adhocs && adhocs[path];
  850. if (adhocType) {
  851. return adhocType;
  852. }
  853. return this.schema.path(path);
  854. };
  855. /**
  856. * Marks the path as having pending changes to write to the db.
  857. *
  858. * _Very helpful when using [Mixed](./schematypes.html#mixed) types._
  859. *
  860. * ####Example:
  861. *
  862. * doc.mixed.type = 'changed';
  863. * doc.markModified('mixed.type');
  864. * doc.save() // changes to mixed.type are now persisted
  865. *
  866. * @param {String} path the path to mark modified
  867. * @api public
  868. */
  869. Document.prototype.markModified = function(path) {
  870. this.$__.activePaths.modify(path);
  871. };
  872. /**
  873. * Clears the modified state on the specified path.
  874. *
  875. * ####Example:
  876. *
  877. * doc.foo = 'bar';
  878. * doc.unmarkModified('foo');
  879. * doc.save() // changes to foo will not be persisted
  880. *
  881. * @param {String} path the path to unmark modified
  882. * @api public
  883. */
  884. Document.prototype.unmarkModified = function(path) {
  885. this.$__.activePaths.init(path);
  886. };
  887. /**
  888. * Don't run validation on this path or persist changes to this path.
  889. *
  890. * ####Example:
  891. *
  892. * doc.foo = null;
  893. * doc.$ignore('foo');
  894. * doc.save() // changes to foo will not be persisted and validators won't be run
  895. *
  896. * @param {String} path the path to ignore
  897. * @api public
  898. */
  899. Document.prototype.$ignore = function(path) {
  900. this.$__.activePaths.ignore(path);
  901. };
  902. /**
  903. * Returns the list of paths that have been modified.
  904. *
  905. * @return {Array}
  906. * @api public
  907. */
  908. Document.prototype.modifiedPaths = function() {
  909. var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
  910. return directModifiedPaths.reduce(function(list, path) {
  911. var parts = path.split('.');
  912. return list.concat(parts.reduce(function(chains, part, i) {
  913. return chains.concat(parts.slice(0, i).concat(part).join('.'));
  914. }, []).filter(function(chain) {
  915. return (list.indexOf(chain) === -1);
  916. }));
  917. }, []);
  918. };
  919. /**
  920. * Returns true if this document was modified, else false.
  921. *
  922. * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified.
  923. *
  924. * ####Example
  925. *
  926. * doc.set('documents.0.title', 'changed');
  927. * doc.isModified() // true
  928. * doc.isModified('documents') // true
  929. * doc.isModified('documents.0.title') // true
  930. * doc.isModified('documents otherProp') // true
  931. * doc.isDirectModified('documents') // false
  932. *
  933. * @param {String} [path] optional
  934. * @return {Boolean}
  935. * @api public
  936. */
  937. Document.prototype.isModified = function(paths) {
  938. if (paths) {
  939. if (!Array.isArray(paths)) {
  940. paths = paths.split(' ');
  941. }
  942. var modified = this.modifiedPaths();
  943. var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
  944. var isModifiedChild = paths.some(function(path) {
  945. return !!~modified.indexOf(path);
  946. });
  947. return isModifiedChild || paths.some(function(path) {
  948. return directModifiedPaths.some(function(mod) {
  949. return mod === path || path.indexOf(mod + '.') === 0;
  950. });
  951. });
  952. }
  953. return this.$__.activePaths.some('modify');
  954. };
  955. /**
  956. * Checks if a path is set to its default.
  957. *
  958. * ####Example
  959. *
  960. * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
  961. * var m = new MyModel();
  962. * m.$isDefault('name'); // true
  963. *
  964. * @param {String} [path]
  965. * @return {Boolean}
  966. * @method $isDefault
  967. * @api public
  968. */
  969. Document.prototype.$isDefault = function(path) {
  970. return (path in this.$__.activePaths.states.default);
  971. };
  972. /**
  973. * Returns true if `path` was directly set and modified, else false.
  974. *
  975. * ####Example
  976. *
  977. * doc.set('documents.0.title', 'changed');
  978. * doc.isDirectModified('documents.0.title') // true
  979. * doc.isDirectModified('documents') // false
  980. *
  981. * @param {String} path
  982. * @return {Boolean}
  983. * @api public
  984. */
  985. Document.prototype.isDirectModified = function(path) {
  986. return (path in this.$__.activePaths.states.modify);
  987. };
  988. /**
  989. * Checks if `path` was initialized.
  990. *
  991. * @param {String} path
  992. * @return {Boolean}
  993. * @api public
  994. */
  995. Document.prototype.isInit = function(path) {
  996. return (path in this.$__.activePaths.states.init);
  997. };
  998. /**
  999. * Checks if `path` was selected in the source query which initialized this document.
  1000. *
  1001. * ####Example
  1002. *
  1003. * Thing.findOne().select('name').exec(function (err, doc) {
  1004. * doc.isSelected('name') // true
  1005. * doc.isSelected('age') // false
  1006. * })
  1007. *
  1008. * @param {String} path
  1009. * @return {Boolean}
  1010. * @api public
  1011. */
  1012. Document.prototype.isSelected = function isSelected(path) {
  1013. if (this.$__.selected) {
  1014. if (path === '_id') {
  1015. return this.$__.selected._id !== 0;
  1016. }
  1017. var paths = Object.keys(this.$__.selected),
  1018. i = paths.length,
  1019. inclusive = false,
  1020. cur;
  1021. if (i === 1 && paths[0] === '_id') {
  1022. // only _id was selected.
  1023. return this.$__.selected._id === 0;
  1024. }
  1025. while (i--) {
  1026. cur = paths[i];
  1027. if (cur === '_id') {
  1028. continue;
  1029. }
  1030. inclusive = !!this.$__.selected[cur];
  1031. break;
  1032. }
  1033. if (path in this.$__.selected) {
  1034. return inclusive;
  1035. }
  1036. i = paths.length;
  1037. var pathDot = path + '.';
  1038. while (i--) {
  1039. cur = paths[i];
  1040. if (cur === '_id') {
  1041. continue;
  1042. }
  1043. if (cur.indexOf(pathDot) === 0) {
  1044. return inclusive;
  1045. }
  1046. if (pathDot.indexOf(cur + '.') === 0) {
  1047. return inclusive;
  1048. }
  1049. }
  1050. return !inclusive;
  1051. }
  1052. return true;
  1053. };
  1054. /**
  1055. * Executes registered validation rules for this document.
  1056. *
  1057. * ####Note:
  1058. *
  1059. * 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`.
  1060. *
  1061. * ####Example:
  1062. *
  1063. * doc.validate(function (err) {
  1064. * if (err) handleError(err);
  1065. * else // validation passed
  1066. * });
  1067. *
  1068. * @param {Object} optional options internal options
  1069. * @param {Function} callback optional callback called after validation completes, passing an error if one occurred
  1070. * @return {Promise} Promise
  1071. * @api public
  1072. */
  1073. Document.prototype.validate = function(options, callback) {
  1074. if (typeof options === 'function') {
  1075. callback = options;
  1076. options = null;
  1077. }
  1078. this.$__validate(callback);
  1079. };
  1080. /*!
  1081. * ignore
  1082. */
  1083. function _getPathsToValidate(doc) {
  1084. // only validate required fields when necessary
  1085. var paths = Object.keys(doc.$__.activePaths.states.require).filter(function(path) {
  1086. if (!doc.isSelected(path) && !doc.isModified(path)) {
  1087. return false;
  1088. }
  1089. var p = doc.schema.path(path);
  1090. if (typeof p.originalRequiredValue === 'function') {
  1091. return p.originalRequiredValue.call(doc);
  1092. }
  1093. return true;
  1094. });
  1095. paths = paths.concat(Object.keys(doc.$__.activePaths.states.init));
  1096. paths = paths.concat(Object.keys(doc.$__.activePaths.states.modify));
  1097. paths = paths.concat(Object.keys(doc.$__.activePaths.states.default));
  1098. // gh-661: if a whole array is modified, make sure to run validation on all
  1099. // the children as well
  1100. for (var i = 0; i < paths.length; ++i) {
  1101. var path = paths[i];
  1102. var val = doc.getValue(path);
  1103. if (val && val.isMongooseArray && !Buffer.isBuffer(val) && !val.isMongooseDocumentArray) {
  1104. var numElements = val.length;
  1105. for (var j = 0; j < numElements; ++j) {
  1106. paths.push(path + '.' + j);
  1107. }
  1108. }
  1109. }
  1110. var flattenOptions = { skipArrays: true };
  1111. for (i = 0; i < paths.length; ++i) {
  1112. var pathToCheck = paths[i];
  1113. if (doc.schema.nested[pathToCheck]) {
  1114. var _v = doc.getValue(pathToCheck);
  1115. if (isMongooseObject(_v)) {
  1116. _v = _v.toObject({ transform: false });
  1117. }
  1118. var flat = flatten(_v, '', flattenOptions);
  1119. var _subpaths = Object.keys(flat).map(function(p) {
  1120. return pathToCheck + '.' + p;
  1121. });
  1122. paths = paths.concat(_subpaths);
  1123. }
  1124. }
  1125. return paths;
  1126. }
  1127. /*!
  1128. * ignore
  1129. */
  1130. Document.prototype.$__validate = function(callback) {
  1131. var _this = this;
  1132. var _complete = function() {
  1133. var err = _this.$__.validationError;
  1134. _this.$__.validationError = undefined;
  1135. _this.emit('validate', _this);
  1136. if (err) {
  1137. for (var key in err.errors) {
  1138. // Make sure cast errors persist
  1139. if (!_this.__parent && err.errors[key] instanceof MongooseError.CastError) {
  1140. _this.invalidate(key, err.errors[key]);
  1141. }
  1142. }
  1143. return err;
  1144. }
  1145. };
  1146. // only validate required fields when necessary
  1147. var paths = _getPathsToValidate(this);
  1148. if (paths.length === 0) {
  1149. process.nextTick(function() {
  1150. var err = _complete();
  1151. if (err) {
  1152. callback(err);
  1153. return;
  1154. }
  1155. callback();
  1156. });
  1157. }
  1158. var validating = {},
  1159. total = 0;
  1160. var complete = function() {
  1161. var err = _complete();
  1162. if (err) {
  1163. callback(err);
  1164. return;
  1165. }
  1166. callback();
  1167. };
  1168. var validatePath = function(path) {
  1169. if (validating[path]) {
  1170. return;
  1171. }
  1172. validating[path] = true;
  1173. total++;
  1174. process.nextTick(function() {
  1175. var p = _this.schema.path(path);
  1176. if (!p) {
  1177. return --total || complete();
  1178. }
  1179. // If user marked as invalid or there was a cast error, don't validate
  1180. if (!_this.$isValid(path)) {
  1181. --total || complete();
  1182. return;
  1183. }
  1184. var val = _this.getValue(path);
  1185. p.doValidate(val, function(err) {
  1186. if (err) {
  1187. _this.invalidate(path, err, undefined, true);
  1188. }
  1189. --total || complete();
  1190. }, _this);
  1191. });
  1192. };
  1193. paths.forEach(validatePath);
  1194. };
  1195. /**
  1196. * Executes registered validation rules (skipping asynchronous validators) for this document.
  1197. *
  1198. * ####Note:
  1199. *
  1200. * This method is useful if you need synchronous validation.
  1201. *
  1202. * ####Example:
  1203. *
  1204. * var err = doc.validateSync();
  1205. * if ( err ){
  1206. * handleError( err );
  1207. * } else {
  1208. * // validation passed
  1209. * }
  1210. *
  1211. * @param {Array|string} pathsToValidate only validate the given paths
  1212. * @return {MongooseError|undefined} MongooseError if there are errors during validation, or undefined if there is no error.
  1213. * @api public
  1214. */
  1215. Document.prototype.validateSync = function(pathsToValidate) {
  1216. var _this = this;
  1217. if (typeof pathsToValidate === 'string') {
  1218. pathsToValidate = pathsToValidate.split(' ');
  1219. }
  1220. // only validate required fields when necessary
  1221. var paths = _getPathsToValidate(this);
  1222. if (pathsToValidate && pathsToValidate.length) {
  1223. var tmp = [];
  1224. for (var i = 0; i < paths.length; ++i) {
  1225. if (pathsToValidate.indexOf(paths[i]) !== -1) {
  1226. tmp.push(paths[i]);
  1227. }
  1228. }
  1229. paths = tmp;
  1230. }
  1231. var validating = {};
  1232. paths.forEach(function(path) {
  1233. if (validating[path]) {
  1234. return;
  1235. }
  1236. validating[path] = true;
  1237. var p = _this.schema.path(path);
  1238. if (!p) {
  1239. return;
  1240. }
  1241. if (!_this.$isValid(path)) {
  1242. return;
  1243. }
  1244. var val = _this.getValue(path);
  1245. var err = p.doValidateSync(val, _this);
  1246. if (err) {
  1247. _this.invalidate(path, err, undefined, true);
  1248. }
  1249. });
  1250. var err = _this.$__.validationError;
  1251. _this.$__.validationError = undefined;
  1252. _this.emit('validate', _this);
  1253. if (err) {
  1254. for (var key in err.errors) {
  1255. // Make sure cast errors persist
  1256. if (err.errors[key] instanceof MongooseError.CastError) {
  1257. _this.invalidate(key, err.errors[key]);
  1258. }
  1259. }
  1260. }
  1261. return err;
  1262. };
  1263. /**
  1264. * Marks a path as invalid, causing validation to fail.
  1265. *
  1266. * The `errorMsg` argument will become the message of the `ValidationError`.
  1267. *
  1268. * The `value` argument (if passed) will be available through the `ValidationError.value` property.
  1269. *
  1270. * doc.invalidate('size', 'must be less than 20', 14);
  1271. * doc.validate(function (err) {
  1272. * console.log(err)
  1273. * // prints
  1274. * { message: 'Validation failed',
  1275. * name: 'ValidationError',
  1276. * errors:
  1277. * { size:
  1278. * { message: 'must be less than 20',
  1279. * name: 'ValidatorError',
  1280. * path: 'size',
  1281. * type: 'user defined',
  1282. * value: 14 } } }
  1283. * })
  1284. *
  1285. * @param {String} path the field to invalidate
  1286. * @param {String|Error} errorMsg the error which states the reason `path` was invalid
  1287. * @param {Object|String|Number|any} value optional invalid value
  1288. * @param {String} [kind] optional `kind` property for the error
  1289. * @return {ValidationError} the current ValidationError, with all currently invalidated paths
  1290. * @api public
  1291. */
  1292. Document.prototype.invalidate = function(path, err, val, kind) {
  1293. if (!this.$__.validationError) {
  1294. this.$__.validationError = new ValidationError(this);
  1295. }
  1296. if (this.$__.validationError.errors[path]) {
  1297. return;
  1298. }
  1299. if (!err || typeof err === 'string') {
  1300. err = new ValidatorError({
  1301. path: path,
  1302. message: err,
  1303. type: kind || 'user defined',
  1304. value: val
  1305. });
  1306. }
  1307. if (this.$__.validationError === err) {
  1308. return this.$__.validationError;
  1309. }
  1310. this.$__.validationError.errors[path] = err;
  1311. return this.$__.validationError;
  1312. };
  1313. /**
  1314. * Marks a path as valid, removing existing validation errors.
  1315. *
  1316. * @param {String} path the field to mark as valid
  1317. * @api private
  1318. * @method $markValid
  1319. * @receiver Document
  1320. */
  1321. Document.prototype.$markValid = function(path) {
  1322. if (!this.$__.validationError || !this.$__.validationError.errors[path]) {
  1323. return;
  1324. }
  1325. delete this.$__.validationError.errors[path];
  1326. if (Object.keys(this.$__.validationError.errors).length === 0) {
  1327. this.$__.validationError = null;
  1328. }
  1329. };
  1330. /**
  1331. * Checks if a path is invalid
  1332. *
  1333. * @param {String} path the field to check
  1334. * @method $isValid
  1335. * @api private
  1336. * @receiver Document
  1337. */
  1338. Document.prototype.$isValid = function(path) {
  1339. return !this.$__.validationError || !this.$__.validationError.errors[path];
  1340. };
  1341. /**
  1342. * Resets the internal modified state of this document.
  1343. *
  1344. * @api private
  1345. * @return {Document}
  1346. * @method $__reset
  1347. * @memberOf Document
  1348. */
  1349. Document.prototype.$__reset = function reset() {
  1350. var _this = this;
  1351. DocumentArray || (DocumentArray = require('./types/documentarray'));
  1352. this.$__.activePaths
  1353. .map('init', 'modify', function(i) {
  1354. return _this.getValue(i);
  1355. })
  1356. .filter(function(val) {
  1357. return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
  1358. })
  1359. .forEach(function(array) {
  1360. var i = array.length;
  1361. while (i--) {
  1362. var doc = array[i];
  1363. if (!doc) {
  1364. continue;
  1365. }
  1366. doc.$__reset();
  1367. }
  1368. });
  1369. // clear atomics
  1370. this.$__dirty().forEach(function(dirt) {
  1371. var type = dirt.value;
  1372. if (type && type._atomics) {
  1373. type._atomics = {};
  1374. }
  1375. });
  1376. // Clear 'dirty' cache
  1377. this.$__.activePaths.clear('modify');
  1378. this.$__.activePaths.clear('default');
  1379. this.$__.validationError = undefined;
  1380. this.errors = undefined;
  1381. _this = this;
  1382. this.schema.requiredPaths().forEach(function(path) {
  1383. _this.$__.activePaths.require(path);
  1384. });
  1385. return this;
  1386. };
  1387. /**
  1388. * Returns this documents dirty paths / vals.
  1389. *
  1390. * @api private
  1391. * @method $__dirty
  1392. * @memberOf Document
  1393. */
  1394. Document.prototype.$__dirty = function() {
  1395. var _this = this;
  1396. var all = this.$__.activePaths.map('modify', function(path) {
  1397. return {
  1398. path: path,
  1399. value: _this.getValue(path),
  1400. schema: _this.$__path(path)
  1401. };
  1402. });
  1403. // gh-2558: if we had to set a default and the value is not undefined,
  1404. // we have to save as well
  1405. all = all.concat(this.$__.activePaths.map('default', function(path) {
  1406. if (path === '_id' || !_this.getValue(path)) {
  1407. return;
  1408. }
  1409. return {
  1410. path: path,
  1411. value: _this.getValue(path),
  1412. schema: _this.$__path(path)
  1413. };
  1414. }));
  1415. // Sort dirty paths in a flat hierarchy.
  1416. all.sort(function(a, b) {
  1417. return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0));
  1418. });
  1419. // Ignore "foo.a" if "foo" is dirty already.
  1420. var minimal = [],
  1421. lastPath,
  1422. top;
  1423. all.forEach(function(item) {
  1424. if (!item) {
  1425. return;
  1426. }
  1427. if (item.path.indexOf(lastPath) !== 0) {
  1428. lastPath = item.path + '.';
  1429. minimal.push(item);
  1430. top = item;
  1431. } else {
  1432. // special case for top level MongooseArrays
  1433. if (top.value && top.value._atomics && top.value.hasAtomics()) {
  1434. // the `top` array itself and a sub path of `top` are being modified.
  1435. // the only way to honor all of both modifications is through a $set
  1436. // of entire array.
  1437. top.value._atomics = {};
  1438. top.value._atomics.$set = top.value;
  1439. }
  1440. }
  1441. });
  1442. top = lastPath = null;
  1443. return minimal;
  1444. };
  1445. /*!
  1446. * Compiles schemas.
  1447. */
  1448. function compile(tree, proto, prefix, options) {
  1449. var keys = Object.keys(tree),
  1450. i = keys.length,
  1451. limb,
  1452. key;
  1453. while (i--) {
  1454. key = keys[i];
  1455. limb = tree[key];
  1456. defineKey(key,
  1457. ((utils.getFunctionName(limb.constructor) === 'Object'
  1458. && Object.keys(limb).length)
  1459. && (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type))
  1460. ? limb
  1461. : null)
  1462. , proto
  1463. , prefix
  1464. , keys
  1465. , options);
  1466. }
  1467. }
  1468. // gets descriptors for all properties of `object`
  1469. // makes all properties non-enumerable to match previous behavior to #2211
  1470. function getOwnPropertyDescriptors(object) {
  1471. var result = {};
  1472. Object.getOwnPropertyNames(object).forEach(function(key) {
  1473. result[key] = Object.getOwnPropertyDescriptor(object, key);
  1474. result[key].enumerable = true;
  1475. });
  1476. return result;
  1477. }
  1478. /*!
  1479. * Defines the accessor named prop on the incoming prototype.
  1480. */
  1481. function defineKey(prop, subprops, prototype, prefix, keys, options) {
  1482. var path = (prefix ? prefix + '.' : '') + prop;
  1483. prefix = prefix || '';
  1484. if (subprops) {
  1485. Object.defineProperty(prototype, prop, {
  1486. enumerable: true,
  1487. configurable: true,
  1488. get: function() {
  1489. var _this = this;
  1490. if (!this.$__.getters) {
  1491. this.$__.getters = {};
  1492. }
  1493. if (!this.$__.getters[path]) {
  1494. var nested = Object.create(Object.getPrototypeOf(this), getOwnPropertyDescriptors(this));
  1495. // save scope for nested getters/setters
  1496. if (!prefix) {
  1497. nested.$__.scope = this;
  1498. }
  1499. // shadow inherited getters from sub-objects so
  1500. // thing.nested.nested.nested... doesn't occur (gh-366)
  1501. var i = 0,
  1502. len = keys.length;
  1503. for (; i < len; ++i) {
  1504. // over-write the parents getter without triggering it
  1505. Object.defineProperty(nested, keys[i], {
  1506. enumerable: false, // It doesn't show up.
  1507. writable: true, // We can set it later.
  1508. configurable: true, // We can Object.defineProperty again.
  1509. value: undefined // It shadows its parent.
  1510. });
  1511. }
  1512. Object.defineProperty(nested, 'toObject', {
  1513. enumerable: true,
  1514. configurable: true,
  1515. writable: false,
  1516. value: function() {
  1517. return _this.get(path);
  1518. }
  1519. });
  1520. Object.defineProperty(nested, 'toJSON', {
  1521. enumerable: true,
  1522. configurable: true,
  1523. writable: false,
  1524. value: function() {
  1525. return _this.get(path);
  1526. }
  1527. });
  1528. Object.defineProperty(nested, '$__isNested', {
  1529. enumerable: true,
  1530. configurable: true,
  1531. writable: false,
  1532. value: true
  1533. });
  1534. compile(subprops, nested, path, options);
  1535. this.$__.getters[path] = nested;
  1536. }
  1537. return this.$__.getters[path];
  1538. },
  1539. set: function(v) {
  1540. if (v instanceof Document) {
  1541. v = v.toObject({ transform: false });
  1542. }
  1543. return (this.$__.scope || this).set(path, v);
  1544. }
  1545. });
  1546. } else {
  1547. Object.defineProperty(prototype, prop, {
  1548. enumerable: true,
  1549. configurable: true,
  1550. get: function() {
  1551. return this.get.call(this.$__.scope || this, path);
  1552. },
  1553. set: function(v) {
  1554. return this.set.call(this.$__.scope || this, path, v);
  1555. }
  1556. });
  1557. }
  1558. }
  1559. /**
  1560. * Assigns/compiles `schema` into this documents prototype.
  1561. *
  1562. * @param {Schema} schema
  1563. * @api private
  1564. * @method $__setSchema
  1565. * @memberOf Document
  1566. */
  1567. Document.prototype.$__setSchema = function(schema) {
  1568. compile(schema.tree, this, undefined, schema.options);
  1569. this.schema = schema;
  1570. };
  1571. /**
  1572. * Get active path that were changed and are arrays
  1573. *
  1574. * @api private
  1575. * @method $__getArrayPathsToValidate
  1576. * @memberOf Document
  1577. */
  1578. Document.prototype.$__getArrayPathsToValidate = function() {
  1579. DocumentArray || (DocumentArray = require('./types/documentarray'));
  1580. // validate all document arrays.
  1581. return this.$__.activePaths
  1582. .map('init', 'modify', function(i) {
  1583. return this.getValue(i);
  1584. }.bind(this))
  1585. .filter(function(val) {
  1586. return val && val instanceof Array && val.isMongooseDocumentArray && val.length;
  1587. }).reduce(function(seed, array) {
  1588. return seed.concat(array);
  1589. }, [])
  1590. .filter(function(doc) {
  1591. return doc;
  1592. });
  1593. };
  1594. /**
  1595. * Get all subdocs (by bfs)
  1596. *
  1597. * @api private
  1598. * @method $__getAllSubdocs
  1599. * @memberOf Document
  1600. */
  1601. Document.prototype.$__getAllSubdocs = function() {
  1602. DocumentArray || (DocumentArray = require('./types/documentarray'));
  1603. Embedded = Embedded || require('./types/embedded');
  1604. function docReducer(seed, path) {
  1605. var val = this[path];
  1606. if (val instanceof Embedded) {
  1607. seed.push(val);
  1608. }
  1609. if (val && val.$isSingleNested) {
  1610. seed = Object.keys(val._doc).reduce(docReducer.bind(val._doc), seed);
  1611. seed.push(val);
  1612. }
  1613. if (val && val.isMongooseDocumentArray) {
  1614. val.forEach(function _docReduce(doc) {
  1615. if (!doc || !doc._doc) {
  1616. return;
  1617. }
  1618. if (doc instanceof Embedded) {
  1619. seed.push(doc);
  1620. }
  1621. seed = Object.keys(doc._doc).reduce(docReducer.bind(doc._doc), seed);
  1622. });
  1623. } else if (val instanceof Document && val.$__isNested) {
  1624. val = val.toObject();
  1625. if (val) {
  1626. seed = Object.keys(val).reduce(docReducer.bind(val), seed);
  1627. }
  1628. }
  1629. return seed;
  1630. }
  1631. var subDocs = Object.keys(this._doc).reduce(docReducer.bind(this), []);
  1632. return subDocs;
  1633. };
  1634. /**
  1635. * Executes methods queued from the Schema definition
  1636. *
  1637. * @api private
  1638. * @method $__registerHooksFromSchema
  1639. * @memberOf Document
  1640. */
  1641. Document.prototype.$__registerHooksFromSchema = function() {
  1642. Embedded = Embedded || require('./types/embedded');
  1643. var Promise = PromiseProvider.get();
  1644. var _this = this;
  1645. var q = _this.schema && _this.schema.callQueue;
  1646. if (!q.length) {
  1647. return _this;
  1648. }
  1649. // we are only interested in 'pre' hooks, and group by point-cut
  1650. var toWrap = q.reduce(function(seed, pair) {
  1651. if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') {
  1652. _this[pair[0]].apply(_this, pair[1]);
  1653. return seed;
  1654. }
  1655. var args = [].slice.call(pair[1]);
  1656. var pointCut = pair[0] === 'on' ? 'post' : args[0];
  1657. if (!(pointCut in seed)) {
  1658. seed[pointCut] = {post: [], pre: []};
  1659. }
  1660. if (pair[0] === 'post') {
  1661. seed[pointCut].post.push(args);
  1662. } else if (pair[0] === 'on') {
  1663. seed[pointCut].push(args);
  1664. } else {
  1665. seed[pointCut].pre.push(args);
  1666. }
  1667. return seed;
  1668. }, {post: []});
  1669. // 'post' hooks are simpler
  1670. toWrap.post.forEach(function(args) {
  1671. _this.on.apply(_this, args);
  1672. });
  1673. delete toWrap.post;
  1674. // 'init' should be synchronous on subdocuments
  1675. if (toWrap.init && _this instanceof Embedded) {
  1676. if (toWrap.init.pre) {
  1677. toWrap.init.pre.forEach(function(args) {
  1678. _this.$pre.apply(_this, args);
  1679. });
  1680. }
  1681. if (toWrap.init.post) {
  1682. toWrap.init.post.forEach(function(args) {
  1683. _this.$post.apply(_this, args);
  1684. });
  1685. }
  1686. delete toWrap.init;
  1687. } else if (toWrap.set) {
  1688. // Set hooks also need to be sync re: gh-3479
  1689. if (toWrap.set.pre) {
  1690. toWrap.set.pre.forEach(function(args) {
  1691. _this.$pre.apply(_this, args);
  1692. });
  1693. }
  1694. if (toWrap.set.post) {
  1695. toWrap.set.post.forEach(function(args) {
  1696. _this.$post.apply(_this, args);
  1697. });
  1698. }
  1699. delete toWrap.set;
  1700. }
  1701. Object.keys(toWrap).forEach(function(pointCut) {
  1702. // this is so we can wrap everything into a promise;
  1703. var newName = ('$__original_' + pointCut);
  1704. if (!_this[pointCut]) {
  1705. return;
  1706. }
  1707. _this[newName] = _this[pointCut];
  1708. _this[pointCut] = function wrappedPointCut() {
  1709. var args = [].slice.call(arguments);
  1710. var lastArg = args.pop();
  1711. var fn;
  1712. var originalError = new Error();
  1713. var $results;
  1714. if (lastArg && typeof lastArg !== 'function') {
  1715. args.push(lastArg);
  1716. } else {
  1717. fn = lastArg;
  1718. }
  1719. var promise = new Promise.ES6(function(resolve, reject) {
  1720. args.push(function(error) {
  1721. if (error) {
  1722. // gh-2633: since VersionError is very generic, take the
  1723. // stack trace of the original save() function call rather
  1724. // than the async trace
  1725. if (error instanceof VersionError) {
  1726. error.stack = originalError.stack;
  1727. }
  1728. _this.$__handleReject(error);
  1729. reject(error);
  1730. return;
  1731. }
  1732. // There may be multiple results and promise libs other than
  1733. // mpromise don't support passing multiple values to `resolve()`
  1734. $results = Array.prototype.slice.call(arguments, 1);
  1735. resolve.apply(promise, $results);
  1736. });
  1737. _this[newName].apply(_this, args);
  1738. });
  1739. if (fn) {
  1740. if (_this.constructor.$wrapCallback) {
  1741. fn = _this.constructor.$wrapCallback(fn);
  1742. }
  1743. return promise.then(
  1744. function() {
  1745. process.nextTick(function() {
  1746. fn.apply(null, [null].concat($results));
  1747. });
  1748. },
  1749. function(error) {
  1750. process.nextTick(function() {
  1751. fn(error);
  1752. });
  1753. });
  1754. }
  1755. return promise;
  1756. };
  1757. toWrap[pointCut].pre.forEach(function(args) {
  1758. args[0] = newName;
  1759. _this.$pre.apply(_this, args);
  1760. });
  1761. toWrap[pointCut].post.forEach(function(args) {
  1762. args[0] = newName;
  1763. _this.$post.apply(_this, args);
  1764. });
  1765. });
  1766. return _this;
  1767. };
  1768. Document.prototype.$__handleReject = function handleReject(err) {
  1769. // emit on the Model if listening
  1770. if (this.listeners('error').length) {
  1771. this.emit('error', err);
  1772. } else if (this.constructor.listeners && this.constructor.listeners('error').length) {
  1773. this.constructor.emit('error', err);
  1774. } else if (this.listeners && this.listeners('error').length) {
  1775. this.emit('error', err);
  1776. }
  1777. };
  1778. /**
  1779. * Internal helper for toObject() and toJSON() that doesn't manipulate options
  1780. *
  1781. * @api private
  1782. * @method $toObject
  1783. * @memberOf Document
  1784. */
  1785. Document.prototype.$toObject = function(options, json) {
  1786. var defaultOptions = {
  1787. transform: true,
  1788. json: json,
  1789. retainKeyOrder: this.schema.options.retainKeyOrder
  1790. };
  1791. // _isNested will only be true if this is not the top level document, we
  1792. // should never depopulate
  1793. if (options && options.depopulate && options._isNested && this.$__.wasPopulated) {
  1794. // populated paths that we set to a document
  1795. return clone(this._id, options);
  1796. }
  1797. // When internally saving this document we always pass options,
  1798. // bypassing the custom schema options.
  1799. if (!(options && utils.getFunctionName(options.constructor) === 'Object') ||
  1800. (options && options._useSchemaOptions)) {
  1801. if (json) {
  1802. options = this.schema.options.toJSON ?
  1803. clone(this.schema.options.toJSON) :
  1804. {};
  1805. options.json = true;
  1806. options._useSchemaOptions = true;
  1807. } else {
  1808. options = this.schema.options.toObject ?
  1809. clone(this.schema.options.toObject) :
  1810. {};
  1811. options.json = false;
  1812. options._useSchemaOptions = true;
  1813. }
  1814. }
  1815. for (var key in defaultOptions) {
  1816. if (options[key] === undefined) {
  1817. options[key] = defaultOptions[key];
  1818. }
  1819. }
  1820. ('minimize' in options) || (options.minimize = this.schema.options.minimize);
  1821. // remember the root transform function
  1822. // to save it from being overwritten by sub-transform functions
  1823. var originalTransform = options.transform;
  1824. options._isNested = true;
  1825. var ret = clone(this._doc, options) || {};
  1826. if (options.getters) {
  1827. applyGetters(this, ret, 'paths', options);
  1828. // applyGetters for paths will add nested empty objects;
  1829. // if minimize is set, we need to remove them.
  1830. if (options.minimize) {
  1831. ret = minimize(ret) || {};
  1832. }
  1833. }
  1834. if (options.virtuals || options.getters && options.virtuals !== false) {
  1835. applyGetters(this, ret, 'virtuals', options);
  1836. }
  1837. if (options.versionKey === false && this.schema.options.versionKey) {
  1838. delete ret[this.schema.options.versionKey];
  1839. }
  1840. var transform = options.transform;
  1841. // In the case where a subdocument has its own transform function, we need to
  1842. // check and see if the parent has a transform (options.transform) and if the
  1843. // child schema has a transform (this.schema.options.toObject) In this case,
  1844. // we need to adjust options.transform to be the child schema's transform and
  1845. // not the parent schema's
  1846. if (transform === true ||
  1847. (this.schema.options.toObject && transform)) {
  1848. var opts = options.json ? this.schema.options.toJSON : this.schema.options.toObject;
  1849. if (opts) {
  1850. transform = (typeof options.transform === 'function' ? options.transform : opts.transform);
  1851. }
  1852. } else {
  1853. options.transform = originalTransform;
  1854. }
  1855. if (typeof transform === 'function') {
  1856. var xformed = transform(this, ret, options);
  1857. if (typeof xformed !== 'undefined') {
  1858. ret = xformed;
  1859. }
  1860. }
  1861. return ret;
  1862. };
  1863. /**
  1864. * Converts this document into a plain javascript object, ready for storage in MongoDB.
  1865. *
  1866. * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage.
  1867. *
  1868. * ####Options:
  1869. *
  1870. * - `getters` apply all getters (path and virtual getters)
  1871. * - `virtuals` apply virtual getters (can override `getters` option)
  1872. * - `minimize` remove empty objects (defaults to true)
  1873. * - `transform` a transform function to apply to the resulting document before returning
  1874. * - `depopulate` depopulate any populated paths, replacing them with their original refs (defaults to false)
  1875. * - `versionKey` whether to include the version key (defaults to true)
  1876. * - `retainKeyOrder` keep the order of object keys. If this is set to true, `Object.keys(new Doc({ a: 1, b: 2}).toObject())` will always produce `['a', 'b']` (defaults to false)
  1877. *
  1878. * ####Getters/Virtuals
  1879. *
  1880. * Example of only applying path getters
  1881. *
  1882. * doc.toObject({ getters: true, virtuals: false })
  1883. *
  1884. * Example of only applying virtual getters
  1885. *
  1886. * doc.toObject({ virtuals: true })
  1887. *
  1888. * Example of applying both path and virtual getters
  1889. *
  1890. * doc.toObject({ getters: true })
  1891. *
  1892. * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument.
  1893. *
  1894. * schema.set('toObject', { virtuals: true })
  1895. *
  1896. * ####Transform
  1897. *
  1898. * 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.
  1899. *
  1900. * Transform functions receive three arguments
  1901. *
  1902. * function (doc, ret, options) {}
  1903. *
  1904. * - `doc` The mongoose document which is being converted
  1905. * - `ret` The plain object representation which has been converted
  1906. * - `options` The options in use (either schema options or the options passed inline)
  1907. *
  1908. * ####Example
  1909. *
  1910. * // specify the transform schema option
  1911. * if (!schema.options.toObject) schema.options.toObject = {};
  1912. * schema.options.toObject.transform = function (doc, ret, options) {
  1913. * // remove the _id of every document before returning the result
  1914. * delete ret._id;
  1915. * return ret;
  1916. * }
  1917. *
  1918. * // without the transformation in the schema
  1919. * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  1920. *
  1921. * // with the transformation
  1922. * doc.toObject(); // { name: 'Wreck-it Ralph' }
  1923. *
  1924. * With transformations we can do a lot more than remove properties. We can even return completely new customized objects:
  1925. *
  1926. * if (!schema.options.toObject) schema.options.toObject = {};
  1927. * schema.options.toObject.transform = function (doc, ret, options) {
  1928. * return { movie: ret.name }
  1929. * }
  1930. *
  1931. * // without the transformation in the schema
  1932. * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  1933. *
  1934. * // with the transformation
  1935. * doc.toObject(); // { movie: 'Wreck-it Ralph' }
  1936. *
  1937. * _Note: if a transform function returns `undefined`, the return value will be ignored._
  1938. *
  1939. * Transformations may also be applied inline, overridding any transform set in the options:
  1940. *
  1941. * function xform (doc, ret, options) {
  1942. * return { inline: ret.name, custom: true }
  1943. * }
  1944. *
  1945. * // pass the transform as an inline option
  1946. * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
  1947. *
  1948. * _Note: if you call `toObject` and pass any options, the transform declared in your schema options will __not__ be applied. To force its application pass `transform: true`_
  1949. *
  1950. * if (!schema.options.toObject) schema.options.toObject = {};
  1951. * schema.options.toObject.hide = '_id';
  1952. * schema.options.toObject.transform = function (doc, ret, options) {
  1953. * if (options.hide) {
  1954. * options.hide.split(' ').forEach(function (prop) {
  1955. * delete ret[prop];
  1956. * });
  1957. * }
  1958. * return ret;
  1959. * }
  1960. *
  1961. * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
  1962. * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
  1963. * doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
  1964. * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }
  1965. *
  1966. * Transforms are applied _only to the document and are not applied to sub-documents_.
  1967. *
  1968. * Transforms, like all of these options, are also available for `toJSON`.
  1969. *
  1970. * See [schema options](/docs/guide.html#toObject) for some more details.
  1971. *
  1972. * _During save, no custom options are applied to the document before being sent to the database._
  1973. *
  1974. * @param {Object} [options]
  1975. * @return {Object} js object
  1976. * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html
  1977. * @api public
  1978. */
  1979. Document.prototype.toObject = function(options) {
  1980. return this.$toObject(options);
  1981. };
  1982. /*!
  1983. * Minimizes an object, removing undefined values and empty objects
  1984. *
  1985. * @param {Object} object to minimize
  1986. * @return {Object}
  1987. */
  1988. function minimize(obj) {
  1989. var keys = Object.keys(obj),
  1990. i = keys.length,
  1991. hasKeys,
  1992. key,
  1993. val;
  1994. while (i--) {
  1995. key = keys[i];
  1996. val = obj[key];
  1997. if (utils.isObject(val)) {
  1998. obj[key] = minimize(val);
  1999. }
  2000. if (undefined === obj[key]) {
  2001. delete obj[key];
  2002. continue;
  2003. }
  2004. hasKeys = true;
  2005. }
  2006. return hasKeys
  2007. ? obj
  2008. : undefined;
  2009. }
  2010. /*!
  2011. * Applies virtuals properties to `json`.
  2012. *
  2013. * @param {Document} self
  2014. * @param {Object} json
  2015. * @param {String} type either `virtuals` or `paths`
  2016. * @return {Object} `json`
  2017. */
  2018. function applyGetters(self, json, type, options) {
  2019. var schema = self.schema,
  2020. paths = Object.keys(schema[type]),
  2021. i = paths.length,
  2022. path;
  2023. while (i--) {
  2024. path = paths[i];
  2025. var parts = path.split('.'),
  2026. plen = parts.length,
  2027. last = plen - 1,
  2028. branch = json,
  2029. part;
  2030. for (var ii = 0; ii < plen; ++ii) {
  2031. part = parts[ii];
  2032. if (ii === last) {
  2033. branch[part] = clone(self.get(path), options);
  2034. } else {
  2035. branch = branch[part] || (branch[part] = {});
  2036. }
  2037. }
  2038. }
  2039. return json;
  2040. }
  2041. /**
  2042. * The return value of this method is used in calls to JSON.stringify(doc).
  2043. *
  2044. * 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.
  2045. *
  2046. * schema.set('toJSON', { virtuals: true })
  2047. *
  2048. * See [schema options](/docs/guide.html#toJSON) for details.
  2049. *
  2050. * @param {Object} options
  2051. * @return {Object}
  2052. * @see Document#toObject #document_Document-toObject
  2053. * @api public
  2054. */
  2055. Document.prototype.toJSON = function(options) {
  2056. return this.$toObject(options, true);
  2057. };
  2058. /**
  2059. * Helper for console.log
  2060. *
  2061. * @api public
  2062. */
  2063. Document.prototype.inspect = function(options) {
  2064. var isPOJO = options &&
  2065. utils.getFunctionName(options.constructor) === 'Object';
  2066. var opts;
  2067. if (isPOJO) {
  2068. opts = options;
  2069. opts.minimize = false;
  2070. opts.retainKeyOrder = true;
  2071. }
  2072. return this.toObject(opts);
  2073. };
  2074. /**
  2075. * Helper for console.log
  2076. *
  2077. * @api public
  2078. * @method toString
  2079. */
  2080. Document.prototype.toString = function() {
  2081. return inspect(this.inspect());
  2082. };
  2083. /**
  2084. * Returns true if the Document stores the same data as doc.
  2085. *
  2086. * Documents are considered equal when they have matching `_id`s, unless neither
  2087. * document has an `_id`, in which case this function falls back to using
  2088. * `deepEqual()`.
  2089. *
  2090. * @param {Document} doc a document to compare
  2091. * @return {Boolean}
  2092. * @api public
  2093. */
  2094. Document.prototype.equals = function(doc) {
  2095. if (!doc) {
  2096. return false;
  2097. }
  2098. var tid = this.get('_id');
  2099. var docid = doc.get ? doc.get('_id') : doc;
  2100. if (!tid && !docid) {
  2101. return deepEqual(this, doc);
  2102. }
  2103. return tid && tid.equals
  2104. ? tid.equals(docid)
  2105. : tid === docid;
  2106. };
  2107. /**
  2108. * Populates document references, executing the `callback` when complete.
  2109. * If you want to use promises instead, use this function with
  2110. * [`execPopulate()`](#document_Document-execPopulate)
  2111. *
  2112. * ####Example:
  2113. *
  2114. * doc
  2115. * .populate('company')
  2116. * .populate({
  2117. * path: 'notes',
  2118. * match: /airline/,
  2119. * select: 'text',
  2120. * model: 'modelName'
  2121. * options: opts
  2122. * }, function (err, user) {
  2123. * assert(doc._id === user._id) // the document itself is passed
  2124. * })
  2125. *
  2126. * // summary
  2127. * doc.populate(path) // not executed
  2128. * doc.populate(options); // not executed
  2129. * doc.populate(path, callback) // executed
  2130. * doc.populate(options, callback); // executed
  2131. * doc.populate(callback); // executed
  2132. * doc.populate(options).execPopulate() // executed, returns promise
  2133. *
  2134. *
  2135. * ####NOTE:
  2136. *
  2137. * Population does not occur unless a `callback` is passed *or* you explicitly
  2138. * call `execPopulate()`.
  2139. * Passing the same path a second time will overwrite the previous path options.
  2140. * See [Model.populate()](#model_Model.populate) for explaination of options.
  2141. *
  2142. * @see Model.populate #model_Model.populate
  2143. * @see Document.execPopulate #document_Document-execPopulate
  2144. * @param {String|Object} [path] The path to populate or an options object
  2145. * @param {Function} [callback] When passed, population is invoked
  2146. * @api public
  2147. * @return {Document} this
  2148. */
  2149. Document.prototype.populate = function populate() {
  2150. if (arguments.length === 0) {
  2151. return this;
  2152. }
  2153. var pop = this.$__.populate || (this.$__.populate = {});
  2154. var args = utils.args(arguments);
  2155. var fn;
  2156. if (typeof args[args.length - 1] === 'function') {
  2157. fn = args.pop();
  2158. }
  2159. // allow `doc.populate(callback)`
  2160. if (args.length) {
  2161. // use hash to remove duplicate paths
  2162. var res = utils.populate.apply(null, args);
  2163. for (var i = 0; i < res.length; ++i) {
  2164. pop[res[i].path] = res[i];
  2165. }
  2166. }
  2167. if (fn) {
  2168. var paths = utils.object.vals(pop);
  2169. this.$__.populate = undefined;
  2170. paths.__noPromise = true;
  2171. this.constructor.populate(this, paths, fn);
  2172. }
  2173. return this;
  2174. };
  2175. /**
  2176. * Explicitly executes population and returns a promise. Useful for ES2015
  2177. * integration.
  2178. *
  2179. * ####Example:
  2180. *
  2181. * var promise = doc.
  2182. * populate('company').
  2183. * populate({
  2184. * path: 'notes',
  2185. * match: /airline/,
  2186. * select: 'text',
  2187. * model: 'modelName'
  2188. * options: opts
  2189. * }).
  2190. * execPopulate();
  2191. *
  2192. * // summary
  2193. * doc.execPopulate().then(resolve, reject);
  2194. *
  2195. *
  2196. * @see Document.populate #document_Document-populate
  2197. * @api public
  2198. * @return {Promise} promise that resolves to the document when population is done
  2199. */
  2200. Document.prototype.execPopulate = function() {
  2201. var Promise = PromiseProvider.get();
  2202. var _this = this;
  2203. return new Promise.ES6(function(resolve, reject) {
  2204. _this.populate(function(error, res) {
  2205. if (error) {
  2206. reject(error);
  2207. } else {
  2208. resolve(res);
  2209. }
  2210. });
  2211. });
  2212. };
  2213. /**
  2214. * Gets _id(s) used during population of the given `path`.
  2215. *
  2216. * ####Example:
  2217. *
  2218. * Model.findOne().populate('author').exec(function (err, doc) {
  2219. * console.log(doc.author.name) // Dr.Seuss
  2220. * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
  2221. * })
  2222. *
  2223. * If the path was not populated, undefined is returned.
  2224. *
  2225. * @param {String} path
  2226. * @return {Array|ObjectId|Number|Buffer|String|undefined}
  2227. * @api public
  2228. */
  2229. Document.prototype.populated = function(path, val, options) {
  2230. // val and options are internal
  2231. if (val === null || val === void 0) {
  2232. if (!this.$__.populated) {
  2233. return undefined;
  2234. }
  2235. var v = this.$__.populated[path];
  2236. if (v) {
  2237. return v.value;
  2238. }
  2239. return undefined;
  2240. }
  2241. // internal
  2242. if (val === true) {
  2243. if (!this.$__.populated) {
  2244. return undefined;
  2245. }
  2246. return this.$__.populated[path];
  2247. }
  2248. this.$__.populated || (this.$__.populated = {});
  2249. this.$__.populated[path] = {value: val, options: options};
  2250. return val;
  2251. };
  2252. /**
  2253. * Takes a populated field and returns it to its unpopulated state.
  2254. *
  2255. * ####Example:
  2256. *
  2257. * Model.findOne().populate('author').exec(function (err, doc) {
  2258. * console.log(doc.author.name); // Dr.Seuss
  2259. * console.log(doc.depopulate('author'));
  2260. * console.log(doc.author); // '5144cf8050f071d979c118a7'
  2261. * })
  2262. *
  2263. * If the path was not populated, this is a no-op.
  2264. *
  2265. * @param {String} path
  2266. * @see Document.populate #document_Document-populate
  2267. * @api public
  2268. */
  2269. Document.prototype.depopulate = function(path) {
  2270. var populatedIds = this.populated(path);
  2271. if (!populatedIds) {
  2272. return;
  2273. }
  2274. delete this.$__.populated[path];
  2275. this.set(path, populatedIds);
  2276. };
  2277. /**
  2278. * Returns the full path to this document.
  2279. *
  2280. * @param {String} [path]
  2281. * @return {String}
  2282. * @api private
  2283. * @method $__fullPath
  2284. * @memberOf Document
  2285. */
  2286. Document.prototype.$__fullPath = function(path) {
  2287. // overridden in SubDocuments
  2288. return path || '';
  2289. };
  2290. /*!
  2291. * Module exports.
  2292. */
  2293. Document.ValidationError = ValidationError;
  2294. module.exports = exports = Document;