document.js 55 KB

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