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

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