documentarray.js 16 KB

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