index.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. 'use strict';
  2. const ArrayMethods = require('../../array/methods');
  3. const Document = require('../../../document');
  4. const castObjectId = require('../../../cast/objectid');
  5. const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
  6. const internalToObjectOptions = require('../../../options').internalToObjectOptions;
  7. const utils = require('../../../utils');
  8. const isBsonType = require('../../../helpers/isBsonType');
  9. const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
  10. const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol;
  11. const arraySchemaSymbol = require('../../../helpers/symbols').arraySchemaSymbol;
  12. const documentArrayParent = require('../../../helpers/symbols').documentArrayParent;
  13. const methods = {
  14. /*!
  15. * ignore
  16. */
  17. toBSON() {
  18. return this.toObject(internalToObjectOptions);
  19. },
  20. /*!
  21. * ignore
  22. */
  23. getArrayParent() {
  24. return this[arrayParentSymbol];
  25. },
  26. /**
  27. * Overrides MongooseArray#cast
  28. *
  29. * @method _cast
  30. * @api private
  31. * @receiver MongooseDocumentArray
  32. */
  33. _cast(value, index) {
  34. if (this[arraySchemaSymbol] == null) {
  35. return value;
  36. }
  37. let Constructor = this[arraySchemaSymbol].casterConstructor;
  38. const isInstance = Constructor.$isMongooseDocumentArray ?
  39. utils.isMongooseDocumentArray(value) :
  40. value instanceof Constructor;
  41. if (isInstance ||
  42. // Hack re: #5001, see #5005
  43. (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) {
  44. if (!(value[documentArrayParent] && value.__parentArray)) {
  45. // value may have been created using array.create()
  46. value[documentArrayParent] = this[arrayParentSymbol];
  47. value.__parentArray = this;
  48. }
  49. value.$setIndex(index);
  50. return value;
  51. }
  52. if (value === undefined || value === null) {
  53. return null;
  54. }
  55. // handle cast('string') or cast(ObjectId) etc.
  56. // only objects are permitted so we can safely assume that
  57. // non-objects are to be interpreted as _id
  58. if (Buffer.isBuffer(value) ||
  59. isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
  60. value = { _id: value };
  61. }
  62. if (value &&
  63. Constructor.discriminators &&
  64. Constructor.schema &&
  65. Constructor.schema.options &&
  66. Constructor.schema.options.discriminatorKey) {
  67. if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' &&
  68. Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
  69. Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
  70. } else {
  71. const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]);
  72. if (constructorByValue) {
  73. Constructor = constructorByValue;
  74. }
  75. }
  76. }
  77. if (Constructor.$isMongooseDocumentArray) {
  78. return Constructor.cast(value, this, undefined, undefined, index);
  79. }
  80. const ret = new Constructor(value, this, undefined, undefined, index);
  81. ret.isNew = true;
  82. return ret;
  83. },
  84. /**
  85. * Searches array items for the first document with a matching _id.
  86. *
  87. * #### Example:
  88. *
  89. * const embeddedDoc = m.array.id(some_id);
  90. *
  91. * @return {EmbeddedDocument|null} the subdocument or null if not found.
  92. * @param {ObjectId|String|Number|Buffer} id
  93. * @TODO cast to the _id based on schema for proper comparison
  94. * @method id
  95. * @api public
  96. * @memberOf MongooseDocumentArray
  97. */
  98. id(id) {
  99. let casted;
  100. let sid;
  101. let _id;
  102. try {
  103. casted = castObjectId(id).toString();
  104. } catch (e) {
  105. casted = null;
  106. }
  107. for (const val of this) {
  108. if (!val) {
  109. continue;
  110. }
  111. _id = val.get('_id');
  112. if (_id === null || typeof _id === 'undefined') {
  113. continue;
  114. } else if (_id instanceof Document) {
  115. sid || (sid = String(id));
  116. if (sid == _id._id) {
  117. return val;
  118. }
  119. } else if (!isBsonType(id, 'ObjectID') && !isBsonType(_id, 'ObjectID')) {
  120. if (id == _id || utils.deepEqual(id, _id)) {
  121. return val;
  122. }
  123. } else if (casted == _id) {
  124. return val;
  125. }
  126. }
  127. return null;
  128. },
  129. /**
  130. * Returns a native js Array of plain js objects
  131. *
  132. * #### Note:
  133. *
  134. * _Each sub-document is converted to a plain object by calling its `#toObject` method._
  135. *
  136. * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion
  137. * @return {Array}
  138. * @method toObject
  139. * @api public
  140. * @memberOf MongooseDocumentArray
  141. */
  142. toObject(options) {
  143. // `[].concat` coerces the return value into a vanilla JS array, rather
  144. // than a Mongoose array.
  145. return [].concat(this.map(function(doc) {
  146. if (doc == null) {
  147. return null;
  148. }
  149. if (typeof doc.toObject !== 'function') {
  150. return doc;
  151. }
  152. return doc.toObject(options);
  153. }));
  154. },
  155. $toObject() {
  156. return this.constructor.prototype.toObject.apply(this, arguments);
  157. },
  158. /**
  159. * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
  160. *
  161. * @param {Object} [args...]
  162. * @api public
  163. * @method push
  164. * @memberOf MongooseDocumentArray
  165. */
  166. push() {
  167. const ret = ArrayMethods.push.apply(this, arguments);
  168. _updateParentPopulated(this);
  169. return ret;
  170. },
  171. /**
  172. * Pulls items from the array atomically.
  173. *
  174. * @param {Object} [args...]
  175. * @api public
  176. * @method pull
  177. * @memberOf MongooseDocumentArray
  178. */
  179. pull() {
  180. const ret = ArrayMethods.pull.apply(this, arguments);
  181. _updateParentPopulated(this);
  182. return ret;
  183. },
  184. /*!
  185. * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
  186. */
  187. shift() {
  188. const ret = ArrayMethods.shift.apply(this, arguments);
  189. _updateParentPopulated(this);
  190. return ret;
  191. },
  192. /*!
  193. * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
  194. */
  195. splice() {
  196. const ret = ArrayMethods.splice.apply(this, arguments);
  197. _updateParentPopulated(this);
  198. return ret;
  199. },
  200. /**
  201. * Helper for console.log
  202. *
  203. * @method inspect
  204. * @api public
  205. * @memberOf MongooseDocumentArray
  206. */
  207. inspect() {
  208. return this.toObject();
  209. },
  210. /**
  211. * Creates a subdocument casted to this schema.
  212. *
  213. * This is the same subdocument constructor used for casting.
  214. *
  215. * @param {Object} obj the value to cast to this arrays SubDocument schema
  216. * @method create
  217. * @api public
  218. * @memberOf MongooseDocumentArray
  219. */
  220. create(obj) {
  221. let Constructor = this[arraySchemaSymbol].casterConstructor;
  222. if (obj &&
  223. Constructor.discriminators &&
  224. Constructor.schema &&
  225. Constructor.schema.options &&
  226. Constructor.schema.options.discriminatorKey) {
  227. if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' &&
  228. Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
  229. Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
  230. } else {
  231. const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]);
  232. if (constructorByValue) {
  233. Constructor = constructorByValue;
  234. }
  235. }
  236. }
  237. return new Constructor(obj, this);
  238. },
  239. /*!
  240. * ignore
  241. */
  242. notify(event) {
  243. const _this = this;
  244. return function notify(val, _arr) {
  245. _arr = _arr || _this;
  246. let i = _arr.length;
  247. while (i--) {
  248. if (_arr[i] == null) {
  249. continue;
  250. }
  251. switch (event) {
  252. // only swap for save event for now, we may change this to all event types later
  253. case 'save':
  254. val = _this[i];
  255. break;
  256. default:
  257. // NO-OP
  258. break;
  259. }
  260. if (utils.isMongooseArray(_arr[i])) {
  261. notify(val, _arr[i]);
  262. } else if (_arr[i]) {
  263. _arr[i].emit(event, val);
  264. }
  265. }
  266. };
  267. },
  268. set(i, val, skipModified) {
  269. const arr = this.__array;
  270. if (skipModified) {
  271. arr[i] = val;
  272. return this;
  273. }
  274. const value = methods._cast.call(this, val, i);
  275. methods._markModified.call(this, i);
  276. arr[i] = value;
  277. return this;
  278. },
  279. _markModified(elem, embeddedPath) {
  280. const parent = this[arrayParentSymbol];
  281. let dirtyPath;
  282. if (parent) {
  283. dirtyPath = this[arrayPathSymbol];
  284. if (arguments.length) {
  285. if (embeddedPath != null) {
  286. // an embedded doc bubbled up the change
  287. const index = elem.__index;
  288. dirtyPath = dirtyPath + '.' + index + '.' + embeddedPath;
  289. } else {
  290. // directly set an index
  291. dirtyPath = dirtyPath + '.' + elem;
  292. }
  293. }
  294. if (dirtyPath != null && dirtyPath.endsWith('.$')) {
  295. return this;
  296. }
  297. parent.markModified(dirtyPath, arguments.length !== 0 ? elem : parent);
  298. }
  299. return this;
  300. }
  301. };
  302. module.exports = methods;
  303. /*!
  304. * If this is a document array, each element may contain single
  305. * populated paths, so we need to modify the top-level document's
  306. * populated cache. See gh-8247, gh-8265.
  307. */
  308. function _updateParentPopulated(arr) {
  309. const parent = arr[arrayParentSymbol];
  310. if (!parent || parent.$__.populated == null) return;
  311. const populatedPaths = Object.keys(parent.$__.populated).
  312. filter(p => p.startsWith(arr[arrayPathSymbol] + '.'));
  313. for (const path of populatedPaths) {
  314. const remnant = path.slice((arr[arrayPathSymbol] + '.').length);
  315. if (!Array.isArray(parent.$__.populated[path].value)) {
  316. continue;
  317. }
  318. parent.$__.populated[path].value = arr.map(val => val.$populated(remnant));
  319. }
  320. }