Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

documentarray.js 13KB

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