documentarray.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. doc.$__validate(callback);
  210. }
  211. }
  212. };
  213. /**
  214. * Performs local validations first, then validations on each embedded doc.
  215. *
  216. * ####Note:
  217. *
  218. * This method ignores the asynchronous validators.
  219. *
  220. * @return {MongooseError|undefined}
  221. * @api private
  222. */
  223. DocumentArrayPath.prototype.doValidateSync = function(array, scope) {
  224. const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
  225. if (schemaTypeError != null) {
  226. schemaTypeError.$isArrayValidatorError = true;
  227. return schemaTypeError;
  228. }
  229. const count = array && array.length;
  230. let resultError = null;
  231. if (!count) {
  232. return;
  233. }
  234. // handle sparse arrays, do not use array.forEach which does not
  235. // iterate over sparse elements yet reports array.length including
  236. // them :(
  237. for (let i = 0, len = count; i < len; ++i) {
  238. // sidestep sparse entries
  239. let doc = array[i];
  240. if (!doc) {
  241. continue;
  242. }
  243. // If you set the array index directly, the doc might not yet be
  244. // a full fledged mongoose subdoc, so make it into one.
  245. if (!(doc instanceof Subdocument)) {
  246. const Constructor = getConstructor(this.casterConstructor, array[i]);
  247. doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
  248. }
  249. const subdocValidateError = doc.validateSync();
  250. if (subdocValidateError && resultError == null) {
  251. resultError = subdocValidateError;
  252. }
  253. }
  254. return resultError;
  255. };
  256. /*!
  257. * ignore
  258. */
  259. DocumentArrayPath.prototype.getDefault = function(scope) {
  260. let ret = typeof this.defaultValue === 'function'
  261. ? this.defaultValue.call(scope)
  262. : this.defaultValue;
  263. if (ret == null) {
  264. return ret;
  265. }
  266. // lazy load
  267. MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray'));
  268. if (!Array.isArray(ret)) {
  269. ret = [ret];
  270. }
  271. ret = new MongooseDocumentArray(ret, this.path, scope);
  272. for (let i = 0; i < ret.length; ++i) {
  273. const Constructor = getConstructor(this.casterConstructor, ret[i]);
  274. const _subdoc = new Constructor({}, ret, undefined,
  275. undefined, i);
  276. _subdoc.init(ret[i]);
  277. _subdoc.isNew = true;
  278. // Make sure all paths in the subdoc are set to `default` instead
  279. // of `init` since we used `init`.
  280. Object.assign(_subdoc.$__.activePaths.default, _subdoc.$__.activePaths.init);
  281. _subdoc.$__.activePaths.init = {};
  282. ret[i] = _subdoc;
  283. }
  284. return ret;
  285. };
  286. /**
  287. * Casts contents
  288. *
  289. * @param {Object} value
  290. * @param {Document} document that triggers the casting
  291. * @api private
  292. */
  293. DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
  294. // lazy load
  295. MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray'));
  296. let selected;
  297. let subdoc;
  298. const _opts = { transform: false, virtuals: false };
  299. options = options || {};
  300. if (!Array.isArray(value)) {
  301. if (!init && !DocumentArrayPath.options.castNonArrays) {
  302. throw new CastError('DocumentArray', util.inspect(value), this.path, null, this);
  303. }
  304. // gh-2442 mark whole array as modified if we're initializing a doc from
  305. // the db and the path isn't an array in the document
  306. if (!!doc && init) {
  307. doc.markModified(this.path);
  308. }
  309. return this.cast([value], doc, init, prev, options);
  310. }
  311. if (!(value && value.isMongooseDocumentArray) &&
  312. !options.skipDocumentArrayCast) {
  313. value = new MongooseDocumentArray(value, this.path, doc);
  314. } else if (value && value.isMongooseDocumentArray) {
  315. // We need to create a new array, otherwise change tracking will
  316. // update the old doc (gh-4449)
  317. value = new MongooseDocumentArray(value, this.path, doc);
  318. }
  319. if (options.arrayPath != null) {
  320. value[arrayPathSymbol] = options.arrayPath;
  321. }
  322. const len = value.length;
  323. for (let i = 0; i < len; ++i) {
  324. if (!value[i]) {
  325. continue;
  326. }
  327. const Constructor = getConstructor(this.casterConstructor, value[i]);
  328. // Check if the document has a different schema (re gh-3701)
  329. if ((value[i].$__) &&
  330. (!(value[i] instanceof Constructor) || value[i][documentArrayParent] !== doc)) {
  331. value[i] = value[i].toObject({
  332. transform: false,
  333. // Special case: if different model, but same schema, apply virtuals
  334. // re: gh-7898
  335. virtuals: value[i].schema === Constructor.schema
  336. });
  337. }
  338. if (value[i] instanceof Subdocument) {
  339. // Might not have the correct index yet, so ensure it does.
  340. if (value[i].__index == null) {
  341. value[i].$setIndex(i);
  342. }
  343. } else if (value[i] != null) {
  344. if (init) {
  345. if (doc) {
  346. selected || (selected = scopePaths(this, doc.$__.selected, init));
  347. } else {
  348. selected = true;
  349. }
  350. subdoc = new Constructor(null, value, true, selected, i);
  351. value[i] = subdoc.init(value[i]);
  352. } else {
  353. if (prev && typeof prev.id === 'function') {
  354. subdoc = prev.id(value[i]._id);
  355. }
  356. if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), value[i])) {
  357. // handle resetting doc with existing id and same data
  358. subdoc.set(value[i]);
  359. // if set() is hooked it will have no return value
  360. // see gh-746
  361. value[i] = subdoc;
  362. } else {
  363. try {
  364. subdoc = new Constructor(value[i], value, undefined,
  365. undefined, i);
  366. // if set() is hooked it will have no return value
  367. // see gh-746
  368. value[i] = subdoc;
  369. } catch (error) {
  370. const valueInErrorMessage = util.inspect(value[i]);
  371. throw new CastError('embedded', valueInErrorMessage,
  372. value[arrayPathSymbol], error, this);
  373. }
  374. }
  375. }
  376. }
  377. }
  378. return value;
  379. };
  380. /*!
  381. * ignore
  382. */
  383. DocumentArrayPath.prototype.clone = function() {
  384. const options = Object.assign({}, this.options);
  385. const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions);
  386. schematype.validators = this.validators.slice();
  387. schematype.Constructor.discriminators = Object.assign({},
  388. this.Constructor.discriminators);
  389. return schematype;
  390. };
  391. /*!
  392. * Scopes paths selected in a query to this array.
  393. * Necessary for proper default application of subdocument values.
  394. *
  395. * @param {DocumentArrayPath} array - the array to scope `fields` paths
  396. * @param {Object|undefined} fields - the root fields selected in the query
  397. * @param {Boolean|undefined} init - if we are being created part of a query result
  398. */
  399. function scopePaths(array, fields, init) {
  400. if (!(init && fields)) {
  401. return undefined;
  402. }
  403. const path = array.path + '.';
  404. const keys = Object.keys(fields);
  405. let i = keys.length;
  406. const selected = {};
  407. let hasKeys;
  408. let key;
  409. let sub;
  410. while (i--) {
  411. key = keys[i];
  412. if (key.startsWith(path)) {
  413. sub = key.substring(path.length);
  414. if (sub === '$') {
  415. continue;
  416. }
  417. if (sub.startsWith('$.')) {
  418. sub = sub.substr(2);
  419. }
  420. hasKeys || (hasKeys = true);
  421. selected[sub] = fields[key];
  422. }
  423. }
  424. return hasKeys && selected || undefined;
  425. }
  426. /*!
  427. * Module exports.
  428. */
  429. module.exports = DocumentArrayPath;