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

2538 lines
65 KiB

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