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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const CoreMongooseArray = require('./core_array');
  6. const Document = require('../document');
  7. const MongooseArray = require('./array');
  8. const ObjectId = require('./objectid');
  9. const castObjectId = require('../cast/objectid');
  10. const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue;
  11. const internalToObjectOptions = require('../options').internalToObjectOptions;
  12. const util = require('util');
  13. const utils = require('../utils');
  14. const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
  15. const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol;
  16. const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
  17. const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol;
  18. const documentArrayParent = require('../helpers/symbols').documentArrayParent;
  19. /**
  20. * DocumentArray constructor
  21. *
  22. * @param {Array} values
  23. * @param {String} path the path to this array
  24. * @param {Document} doc parent document
  25. * @api private
  26. * @return {MongooseDocumentArray}
  27. * @inherits MongooseArray
  28. * @see http://bit.ly/f6CnZU
  29. */
  30. function MongooseDocumentArray(values, path, doc) {
  31. // TODO: replace this with `new CoreMongooseArray().concat()` when we remove
  32. // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png
  33. const arr = new CoreMongooseArray();
  34. const props = {
  35. isMongooseDocumentArray: true,
  36. validators: [],
  37. _handlers: void 0
  38. };
  39. arr[arrayAtomicsSymbol] = {};
  40. arr[arraySchemaSymbol] = void 0;
  41. if (Array.isArray(values)) {
  42. if (values instanceof CoreMongooseArray &&
  43. values[arrayPathSymbol] === path &&
  44. values[arrayParentSymbol] === doc) {
  45. arr[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]);
  46. }
  47. values.forEach(v => {
  48. arr.push(v);
  49. });
  50. }
  51. arr[arrayPathSymbol] = path;
  52. // Values always have to be passed to the constructor to initialize, since
  53. // otherwise MongooseArray#push will mark the array as modified to the parent.
  54. const keysMA = Object.keys(MongooseArray.mixin);
  55. let numKeys = keysMA.length;
  56. for (let j = 0; j < numKeys; ++j) {
  57. arr[keysMA[j]] = MongooseArray.mixin[keysMA[j]];
  58. }
  59. const keysMDA = Object.keys(MongooseDocumentArray.mixin);
  60. numKeys = keysMDA.length;
  61. for (let i = 0; i < numKeys; ++i) {
  62. arr[keysMDA[i]] = MongooseDocumentArray.mixin[keysMDA[i]];
  63. }
  64. if (util.inspect.custom) {
  65. props[util.inspect.custom] = arr.inspect;
  66. }
  67. const keysP = Object.keys(props);
  68. numKeys = keysP.length;
  69. for (let k = 0; k < numKeys; ++k) {
  70. arr[keysP[k]] = props[keysP[k]];
  71. }
  72. // Because doc comes from the context of another function, doc === global
  73. // can happen if there was a null somewhere up the chain (see #3020 && #3034)
  74. // RB Jun 17, 2015 updated to check for presence of expected paths instead
  75. // to make more proof against unusual node environments
  76. if (doc && doc instanceof Document) {
  77. arr[arrayParentSymbol] = doc;
  78. arr[arraySchemaSymbol] = doc.schema.path(path);
  79. // `schema.path()` doesn't drill into nested arrays properly yet, see
  80. // gh-6398, gh-6602. This is a workaround because nested arrays are
  81. // always plain non-document arrays, so once you get to a document array
  82. // nesting is done. Matryoshka code.
  83. while (arr != null &&
  84. arr[arraySchemaSymbol] != null &&
  85. arr[arraySchemaSymbol].$isMongooseArray &&
  86. !arr[arraySchemaSymbol].$isMongooseDocumentArray) {
  87. arr[arraySchemaSymbol] = arr[arraySchemaSymbol].casterConstructor;
  88. }
  89. // Tricky but this may be a document array embedded in a normal array,
  90. // in which case `path` would point to the embedded array. See #6405, #6398
  91. if (arr[arraySchemaSymbol] && !arr[arraySchemaSymbol].$isMongooseDocumentArray) {
  92. arr[arraySchemaSymbol] = arr[arraySchemaSymbol].casterConstructor;
  93. }
  94. arr._handlers = {
  95. isNew: arr.notify('isNew'),
  96. save: arr.notify('save')
  97. };
  98. doc.on('save', arr._handlers.save);
  99. doc.on('isNew', arr._handlers.isNew);
  100. }
  101. return arr;
  102. }
  103. /*!
  104. * Inherits from MongooseArray
  105. */
  106. MongooseDocumentArray.mixin = {
  107. /*!
  108. * ignore
  109. */
  110. toBSON: function() {
  111. return this.toObject(internalToObjectOptions);
  112. },
  113. /**
  114. * Overrides MongooseArray#cast
  115. *
  116. * @method _cast
  117. * @api private
  118. * @receiver MongooseDocumentArray
  119. */
  120. _cast: function(value, index) {
  121. let Constructor = this[arraySchemaSymbol].casterConstructor;
  122. const isInstance = Constructor.$isMongooseDocumentArray ?
  123. value && value.isMongooseDocumentArray :
  124. value instanceof Constructor;
  125. if (isInstance ||
  126. // Hack re: #5001, see #5005
  127. (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) {
  128. if (!(value[documentArrayParent] && value.__parentArray)) {
  129. // value may have been created using array.create()
  130. value[documentArrayParent] = this[arrayParentSymbol];
  131. value.__parentArray = this;
  132. }
  133. value.$setIndex(index);
  134. return value;
  135. }
  136. if (value === undefined || value === null) {
  137. return null;
  138. }
  139. // handle cast('string') or cast(ObjectId) etc.
  140. // only objects are permitted so we can safely assume that
  141. // non-objects are to be interpreted as _id
  142. if (Buffer.isBuffer(value) ||
  143. value instanceof ObjectId || !utils.isObject(value)) {
  144. value = {_id: value};
  145. }
  146. if (value &&
  147. Constructor.discriminators &&
  148. Constructor.schema &&
  149. Constructor.schema.options &&
  150. Constructor.schema.options.discriminatorKey) {
  151. if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' &&
  152. Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
  153. Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
  154. } else {
  155. const constructorByValue = getDiscriminatorByValue(Constructor, value[Constructor.schema.options.discriminatorKey]);
  156. if (constructorByValue) {
  157. Constructor = constructorByValue;
  158. }
  159. }
  160. }
  161. if (Constructor.$isMongooseDocumentArray) {
  162. return Constructor.cast(value, this, undefined, undefined, index);
  163. }
  164. return new Constructor(value, this, undefined, undefined, index);
  165. },
  166. /**
  167. * Searches array items for the first document with a matching _id.
  168. *
  169. * ####Example:
  170. *
  171. * var embeddedDoc = m.array.id(some_id);
  172. *
  173. * @return {EmbeddedDocument|null} the subdocument or null if not found.
  174. * @param {ObjectId|String|Number|Buffer} id
  175. * @TODO cast to the _id based on schema for proper comparison
  176. * @method id
  177. * @api public
  178. * @receiver MongooseDocumentArray
  179. */
  180. id: function(id) {
  181. let casted;
  182. let sid;
  183. let _id;
  184. try {
  185. casted = castObjectId(id).toString();
  186. } catch (e) {
  187. casted = null;
  188. }
  189. for (let i = 0, l = this.length; i < l; i++) {
  190. if (!this[i]) {
  191. continue;
  192. }
  193. _id = this[i].get('_id');
  194. if (_id === null || typeof _id === 'undefined') {
  195. continue;
  196. } else if (_id instanceof Document) {
  197. sid || (sid = String(id));
  198. if (sid == _id._id) {
  199. return this[i];
  200. }
  201. } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) {
  202. if (utils.deepEqual(id, _id)) {
  203. return this[i];
  204. }
  205. } else if (casted == _id) {
  206. return this[i];
  207. }
  208. }
  209. return null;
  210. },
  211. /**
  212. * Returns a native js Array of plain js objects
  213. *
  214. * ####NOTE:
  215. *
  216. * _Each sub-document is converted to a plain object by calling its `#toObject` method._
  217. *
  218. * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion
  219. * @return {Array}
  220. * @method toObject
  221. * @api public
  222. * @receiver MongooseDocumentArray
  223. */
  224. toObject: function(options) {
  225. return this.map(function(doc) {
  226. try {
  227. return doc.toObject(options);
  228. } catch (e) {
  229. return doc || null;
  230. }
  231. });
  232. },
  233. /**
  234. * Helper for console.log
  235. *
  236. * @method inspect
  237. * @api public
  238. * @receiver MongooseDocumentArray
  239. */
  240. inspect: function() {
  241. return this.toObject();
  242. },
  243. /**
  244. * Creates a subdocument casted to this schema.
  245. *
  246. * This is the same subdocument constructor used for casting.
  247. *
  248. * @param {Object} obj the value to cast to this arrays SubDocument schema
  249. * @method create
  250. * @api public
  251. * @receiver MongooseDocumentArray
  252. */
  253. create: function(obj) {
  254. let Constructor = this[arraySchemaSymbol].casterConstructor;
  255. if (obj &&
  256. Constructor.discriminators &&
  257. Constructor.schema &&
  258. Constructor.schema.options &&
  259. Constructor.schema.options.discriminatorKey) {
  260. if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' &&
  261. Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
  262. Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
  263. } else {
  264. const constructorByValue = getDiscriminatorByValue(Constructor, obj[Constructor.schema.options.discriminatorKey]);
  265. if (constructorByValue) {
  266. Constructor = constructorByValue;
  267. }
  268. }
  269. }
  270. return new Constructor(obj, this);
  271. },
  272. /**
  273. * Creates a fn that notifies all child docs of `event`.
  274. *
  275. * @param {String} event
  276. * @return {Function}
  277. * @method notify
  278. * @api private
  279. * @receiver MongooseDocumentArray
  280. */
  281. notify: function notify(event) {
  282. const _this = this;
  283. return function notify(val, _arr) {
  284. _arr = _arr || _this;
  285. let i = _arr.length;
  286. while (i--) {
  287. if (_arr[i] == null) {
  288. continue;
  289. }
  290. switch (event) {
  291. // only swap for save event for now, we may change this to all event types later
  292. case 'save':
  293. val = _this[i];
  294. break;
  295. default:
  296. // NO-OP
  297. break;
  298. }
  299. if (_arr[i].isMongooseArray) {
  300. notify(val, _arr[i]);
  301. } else if (_arr[i]) {
  302. _arr[i].emit(event, val);
  303. }
  304. }
  305. };
  306. }
  307. };
  308. /*!
  309. * Module exports.
  310. */
  311. module.exports = MongooseDocumentArray;