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 12KB

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