document.js 67 KB

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