documentArray.js 19 KB

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