documentarray.js 16 KB

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