documentarray.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const ArrayType = require('./array');
  6. const CastError = require('../error/cast');
  7. const EventEmitter = require('events').EventEmitter;
  8. const SchemaDocumentArrayOptions =
  9. require('../options/SchemaDocumentArrayOptions');
  10. const SchemaType = require('../schematype');
  11. const SubdocumentPath = require('./SubdocumentPath');
  12. const discriminator = require('../helpers/model/discriminator');
  13. const handleIdOption = require('../helpers/schema/handleIdOption');
  14. const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
  15. const utils = require('../utils');
  16. const getConstructor = require('../helpers/discriminator/getConstructor');
  17. const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
  18. const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
  19. const documentArrayParent = require('../helpers/symbols').documentArrayParent;
  20. let MongooseDocumentArray;
  21. let Subdocument;
  22. /**
  23. * SubdocsArray SchemaType constructor
  24. *
  25. * @param {String} key
  26. * @param {Schema} schema
  27. * @param {Object} options
  28. * @param {Object} schemaOptions
  29. * @inherits SchemaArray
  30. * @api public
  31. */
  32. function DocumentArrayPath(key, schema, options, schemaOptions) {
  33. if (schemaOptions != null && schemaOptions._id != null) {
  34. schema = handleIdOption(schema, schemaOptions);
  35. } else if (options != null && options._id != null) {
  36. schema = handleIdOption(schema, options);
  37. }
  38. const EmbeddedDocument = _createConstructor(schema, options);
  39. EmbeddedDocument.prototype.$basePath = key;
  40. ArrayType.call(this, key, EmbeddedDocument, options);
  41. this.schema = schema;
  42. this.schemaOptions = schemaOptions || {};
  43. this.$isMongooseDocumentArray = true;
  44. this.Constructor = EmbeddedDocument;
  45. EmbeddedDocument.base = schema.base;
  46. const fn = this.defaultValue;
  47. if (!('defaultValue' in this) || fn !== void 0) {
  48. this.default(function() {
  49. let arr = fn.call(this);
  50. if (arr != null && !Array.isArray(arr)) {
  51. arr = [arr];
  52. }
  53. // Leave it up to `cast()` to convert this to a documentarray
  54. return arr;
  55. });
  56. }
  57. const parentSchemaType = this;
  58. this.$embeddedSchemaType = new SchemaType(key + '.$', {
  59. required: this &&
  60. this.schemaOptions &&
  61. this.schemaOptions.required || false
  62. });
  63. this.$embeddedSchemaType.cast = function(value, doc, init) {
  64. return parentSchemaType.cast(value, doc, init)[0];
  65. };
  66. this.$embeddedSchemaType.doValidate = function(value, fn, scope, options) {
  67. const Constructor = getConstructor(this.caster, value);
  68. if (value && !(value instanceof Constructor)) {
  69. value = new Constructor(value, scope, null, null, options && options.index != null ? options.index : null);
  70. }
  71. return SubdocumentPath.prototype.doValidate.call(this, value, fn, scope, options);
  72. };
  73. this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true;
  74. this.$embeddedSchemaType.caster = this.Constructor;
  75. this.$embeddedSchemaType.schema = this.schema;
  76. }
  77. /**
  78. * This schema type's name, to defend against minifiers that mangle
  79. * function names.
  80. *
  81. * @api public
  82. */
  83. DocumentArrayPath.schemaName = 'DocumentArray';
  84. /**
  85. * Options for all document arrays.
  86. *
  87. * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting.
  88. *
  89. * @api public
  90. */
  91. DocumentArrayPath.options = { castNonArrays: true };
  92. /*!
  93. * Inherits from ArrayType.
  94. */
  95. DocumentArrayPath.prototype = Object.create(ArrayType.prototype);
  96. DocumentArrayPath.prototype.constructor = DocumentArrayPath;
  97. DocumentArrayPath.prototype.OptionsConstructor = SchemaDocumentArrayOptions;
  98. /*!
  99. * Ignore
  100. */
  101. function _createConstructor(schema, options, baseClass) {
  102. Subdocument || (Subdocument = require('../types/ArraySubdocument'));
  103. // compile an embedded document for this schema
  104. function EmbeddedDocument(_value, parentArray) {
  105. Subdocument.apply(this, arguments);
  106. if (parentArray == null || parentArray.getArrayParent() == null) {
  107. return;
  108. }
  109. this.$session(parentArray.getArrayParent().$session());
  110. }
  111. schema._preCompile();
  112. const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype;
  113. EmbeddedDocument.prototype = Object.create(proto);
  114. EmbeddedDocument.prototype.$__setSchema(schema);
  115. EmbeddedDocument.schema = schema;
  116. EmbeddedDocument.prototype.constructor = EmbeddedDocument;
  117. EmbeddedDocument.$isArraySubdocument = true;
  118. EmbeddedDocument.events = new EventEmitter();
  119. // apply methods
  120. for (const i in schema.methods) {
  121. EmbeddedDocument.prototype[i] = schema.methods[i];
  122. }
  123. // apply statics
  124. for (const i in schema.statics) {
  125. EmbeddedDocument[i] = schema.statics[i];
  126. }
  127. for (const i in EventEmitter.prototype) {
  128. EmbeddedDocument[i] = EventEmitter.prototype[i];
  129. }
  130. EmbeddedDocument.options = options;
  131. return EmbeddedDocument;
  132. }
  133. /**
  134. * Adds a discriminator to this document array.
  135. *
  136. * #### Example:
  137. * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
  138. * const schema = Schema({ shapes: [shapeSchema] });
  139. *
  140. * const docArrayPath = parentSchema.path('shapes');
  141. * docArrayPath.discriminator('Circle', Schema({ radius: Number }));
  142. *
  143. * @param {String} name
  144. * @param {Schema} schema fields to add to the schema for instances of this sub-class
  145. * @param {Object|string} [options] If string, same as `options.value`.
  146. * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
  147. * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
  148. * @see discriminators /docs/discriminators.html
  149. * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model
  150. * @api public
  151. */
  152. DocumentArrayPath.prototype.discriminator = function(name, schema, options) {
  153. if (typeof name === 'function') {
  154. name = utils.getFunctionName(name);
  155. }
  156. options = options || {};
  157. const tiedValue = utils.isPOJO(options) ? options.value : options;
  158. const clone = typeof options.clone === 'boolean' ? options.clone : true;
  159. if (schema.instanceOfSchema && clone) {
  160. schema = schema.clone();
  161. }
  162. schema = discriminator(this.casterConstructor, name, schema, tiedValue);
  163. const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor);
  164. EmbeddedDocument.baseCasterConstructor = this.casterConstructor;
  165. try {
  166. Object.defineProperty(EmbeddedDocument, 'name', {
  167. value: name
  168. });
  169. } catch (error) {
  170. // Ignore error, only happens on old versions of node
  171. }
  172. this.casterConstructor.discriminators[name] = EmbeddedDocument;
  173. return this.casterConstructor.discriminators[name];
  174. };
  175. /**
  176. * Performs local validations first, then validations on each embedded doc
  177. *
  178. * @api private
  179. */
  180. DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) {
  181. // lazy load
  182. MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray'));
  183. const _this = this;
  184. try {
  185. SchemaType.prototype.doValidate.call(this, array, cb, scope);
  186. } catch (err) {
  187. return fn(err);
  188. }
  189. function cb(err) {
  190. if (err) {
  191. return fn(err);
  192. }
  193. let count = array && array.length;
  194. let error;
  195. if (!count) {
  196. return fn();
  197. }
  198. if (options && options.updateValidator) {
  199. return fn();
  200. }
  201. if (!utils.isMongooseDocumentArray(array)) {
  202. array = new MongooseDocumentArray(array, _this.path, scope);
  203. }
  204. // handle sparse arrays, do not use array.forEach which does not
  205. // iterate over sparse elements yet reports array.length including
  206. // them :(
  207. function callback(err) {
  208. if (err != null) {
  209. error = err;
  210. }
  211. --count || fn(error);
  212. }
  213. for (let i = 0, len = count; i < len; ++i) {
  214. // sidestep sparse entries
  215. let doc = array[i];
  216. if (doc == null) {
  217. --count || fn(error);
  218. continue;
  219. }
  220. // If you set the array index directly, the doc might not yet be
  221. // a full fledged mongoose subdoc, so make it into one.
  222. if (!(doc instanceof Subdocument)) {
  223. const Constructor = getConstructor(_this.casterConstructor, array[i]);
  224. doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
  225. }
  226. if (options != null && options.validateModifiedOnly && !doc.$isModified()) {
  227. --count || fn(error);
  228. continue;
  229. }
  230. doc.$__validate(callback);
  231. }
  232. }
  233. };
  234. /**
  235. * Performs local validations first, then validations on each embedded doc.
  236. *
  237. * #### Note:
  238. *
  239. * This method ignores the asynchronous validators.
  240. *
  241. * @return {MongooseError|undefined}
  242. * @api private
  243. */
  244. DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) {
  245. const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
  246. if (schemaTypeError != null) {
  247. return schemaTypeError;
  248. }
  249. const count = array && array.length;
  250. let resultError = null;
  251. if (!count) {
  252. return;
  253. }
  254. // handle sparse arrays, do not use array.forEach which does not
  255. // iterate over sparse elements yet reports array.length including
  256. // them :(
  257. for (let i = 0, len = count; i < len; ++i) {
  258. // sidestep sparse entries
  259. let doc = array[i];
  260. if (!doc) {
  261. continue;
  262. }
  263. // If you set the array index directly, the doc might not yet be
  264. // a full fledged mongoose subdoc, so make it into one.
  265. if (!(doc instanceof Subdocument)) {
  266. const Constructor = getConstructor(this.casterConstructor, array[i]);
  267. doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
  268. }
  269. if (options != null && options.validateModifiedOnly && !doc.$isModified()) {
  270. continue;
  271. }
  272. const subdocValidateError = doc.validateSync();
  273. if (subdocValidateError && resultError == null) {
  274. resultError = subdocValidateError;
  275. }
  276. }
  277. return resultError;
  278. };
  279. /*!
  280. * ignore
  281. */
  282. DocumentArrayPath.prototype.getDefault = function(scope) {
  283. let ret = typeof this.defaultValue === 'function'
  284. ? this.defaultValue.call(scope)
  285. : this.defaultValue;
  286. if (ret == null) {
  287. return ret;
  288. }
  289. // lazy load
  290. MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray'));
  291. if (!Array.isArray(ret)) {
  292. ret = [ret];
  293. }
  294. ret = new MongooseDocumentArray(ret, this.path, scope);
  295. for (let i = 0; i < ret.length; ++i) {
  296. const Constructor = getConstructor(this.casterConstructor, ret[i]);
  297. const _subdoc = new Constructor({}, ret, undefined,
  298. undefined, i);
  299. _subdoc.$init(ret[i]);
  300. _subdoc.isNew = true;
  301. // Make sure all paths in the subdoc are set to `default` instead
  302. // of `init` since we used `init`.
  303. Object.assign(_subdoc.$__.activePaths.default, _subdoc.$__.activePaths.init);
  304. _subdoc.$__.activePaths.init = {};
  305. ret[i] = _subdoc;
  306. }
  307. return ret;
  308. };
  309. const _toObjectOptions = Object.freeze({ transform: false, virtuals: false });
  310. const initDocumentOptions = Object.freeze({ skipId: true, willInit: true });
  311. /**
  312. * Casts contents
  313. *
  314. * @param {Object} value
  315. * @param {Document} document that triggers the casting
  316. * @api private
  317. */
  318. DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
  319. // lazy load
  320. MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray'));
  321. // Skip casting if `value` is the same as the previous value, no need to cast. See gh-9266
  322. if (value != null && value[arrayPathSymbol] != null && value === prev) {
  323. return value;
  324. }
  325. let selected;
  326. let subdoc;
  327. options = options || {};
  328. if (!Array.isArray(value)) {
  329. if (!init && !DocumentArrayPath.options.castNonArrays) {
  330. throw new CastError('DocumentArray', value, this.path, null, this);
  331. }
  332. // gh-2442 mark whole array as modified if we're initializing a doc from
  333. // the db and the path isn't an array in the document
  334. if (!!doc && init) {
  335. doc.markModified(this.path);
  336. }
  337. return this.cast([value], doc, init, prev, options);
  338. }
  339. // We need to create a new array, otherwise change tracking will
  340. // update the old doc (gh-4449)
  341. if (!options.skipDocumentArrayCast || utils.isMongooseDocumentArray(value)) {
  342. value = new MongooseDocumentArray(value, this.path, doc);
  343. }
  344. if (prev != null) {
  345. value[arrayAtomicsSymbol] = prev[arrayAtomicsSymbol] || {};
  346. }
  347. if (options.arrayPathIndex != null) {
  348. value[arrayPathSymbol] = this.path + '.' + options.arrayPathIndex;
  349. }
  350. const rawArray = utils.isMongooseDocumentArray(value) ? value.__array : value;
  351. const len = rawArray.length;
  352. for (let i = 0; i < len; ++i) {
  353. if (!rawArray[i]) {
  354. continue;
  355. }
  356. const Constructor = getConstructor(this.casterConstructor, rawArray[i]);
  357. // Check if the document has a different schema (re gh-3701)
  358. if (rawArray[i].$__ != null && !(rawArray[i] instanceof Constructor)) {
  359. const spreadDoc = handleSpreadDoc(rawArray[i], true);
  360. if (rawArray[i] !== spreadDoc) {
  361. rawArray[i] = spreadDoc;
  362. } else {
  363. rawArray[i] = rawArray[i].toObject({
  364. transform: false,
  365. // Special case: if different model, but same schema, apply virtuals
  366. // re: gh-7898
  367. virtuals: rawArray[i].schema === Constructor.schema
  368. });
  369. }
  370. }
  371. if (rawArray[i] instanceof Subdocument) {
  372. if (rawArray[i][documentArrayParent] !== doc) {
  373. if (init) {
  374. const subdoc = new Constructor(null, value, initDocumentOptions, selected, i);
  375. rawArray[i] = subdoc.$init(rawArray[i]);
  376. } else {
  377. const subdoc = new Constructor(rawArray[i], value, undefined, undefined, i);
  378. rawArray[i] = subdoc;
  379. }
  380. }
  381. // Might not have the correct index yet, so ensure it does.
  382. if (rawArray[i].__index == null) {
  383. rawArray[i].$setIndex(i);
  384. }
  385. } else if (rawArray[i] != null) {
  386. if (init) {
  387. if (doc) {
  388. selected || (selected = scopePaths(this, doc.$__.selected, init));
  389. } else {
  390. selected = true;
  391. }
  392. subdoc = new Constructor(null, value, initDocumentOptions, selected, i);
  393. rawArray[i] = subdoc.$init(rawArray[i]);
  394. } else {
  395. if (prev && typeof prev.id === 'function') {
  396. subdoc = prev.id(rawArray[i]._id);
  397. }
  398. if (prev && subdoc && utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) {
  399. // handle resetting doc with existing id and same data
  400. subdoc.set(rawArray[i]);
  401. // if set() is hooked it will have no return value
  402. // see gh-746
  403. rawArray[i] = subdoc;
  404. } else {
  405. try {
  406. subdoc = new Constructor(rawArray[i], value, undefined,
  407. undefined, i);
  408. // if set() is hooked it will have no return value
  409. // see gh-746
  410. rawArray[i] = subdoc;
  411. } catch (error) {
  412. throw new CastError('embedded', rawArray[i],
  413. value[arrayPathSymbol], error, this);
  414. }
  415. }
  416. }
  417. }
  418. }
  419. return value;
  420. };
  421. /*!
  422. * ignore
  423. */
  424. DocumentArrayPath.prototype.clone = function() {
  425. const options = Object.assign({}, this.options);
  426. const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions);
  427. schematype.validators = this.validators.slice();
  428. if (this.requiredValidator !== undefined) {
  429. schematype.requiredValidator = this.requiredValidator;
  430. }
  431. schematype.Constructor.discriminators = Object.assign({},
  432. this.Constructor.discriminators);
  433. return schematype;
  434. };
  435. /*!
  436. * ignore
  437. */
  438. DocumentArrayPath.prototype.applyGetters = function(value, scope) {
  439. return SchemaType.prototype.applyGetters.call(this, value, scope);
  440. };
  441. /*!
  442. * Scopes paths selected in a query to this array.
  443. * Necessary for proper default application of subdocument values.
  444. *
  445. * @param {DocumentArrayPath} array - the array to scope `fields` paths
  446. * @param {Object|undefined} fields - the root fields selected in the query
  447. * @param {Boolean|undefined} init - if we are being created part of a query result
  448. */
  449. function scopePaths(array, fields, init) {
  450. if (!(init && fields)) {
  451. return undefined;
  452. }
  453. const path = array.path + '.';
  454. const keys = Object.keys(fields);
  455. let i = keys.length;
  456. const selected = {};
  457. let hasKeys;
  458. let key;
  459. let sub;
  460. while (i--) {
  461. key = keys[i];
  462. if (key.startsWith(path)) {
  463. sub = key.substring(path.length);
  464. if (sub === '$') {
  465. continue;
  466. }
  467. if (sub.startsWith('$.')) {
  468. sub = sub.substring(2);
  469. }
  470. hasKeys || (hasKeys = true);
  471. selected[sub] = fields[key];
  472. }
  473. }
  474. return hasKeys && selected || undefined;
  475. }
  476. /**
  477. * Sets a default option for all DocumentArray instances.
  478. *
  479. * #### Example:
  480. *
  481. * // Make all numbers have option `min` equal to 0.
  482. * mongoose.Schema.DocumentArray.set('_id', false);
  483. *
  484. * @param {String} option - The option you'd like to set the value for
  485. * @param {*} value - value for option
  486. * @return {undefined}
  487. * @function set
  488. * @static
  489. * @api public
  490. */
  491. DocumentArrayPath.defaultOptions = {};
  492. DocumentArrayPath.set = SchemaType.set;
  493. /*!
  494. * Module exports.
  495. */
  496. module.exports = DocumentArrayPath;