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.

array.js 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const $exists = require('./operators/exists');
  6. const $type = require('./operators/type');
  7. const MongooseError = require('../error/mongooseError');
  8. const SchemaType = require('../schematype');
  9. const CastError = SchemaType.CastError;
  10. const Types = {
  11. Array: SchemaArray,
  12. Boolean: require('./boolean'),
  13. Date: require('./date'),
  14. Number: require('./number'),
  15. String: require('./string'),
  16. ObjectId: require('./objectid'),
  17. Buffer: require('./buffer'),
  18. Map: require('./map')
  19. };
  20. const Mixed = require('./mixed');
  21. const cast = require('../cast');
  22. const get = require('../helpers/get');
  23. const util = require('util');
  24. const utils = require('../utils');
  25. const castToNumber = require('./operators/helpers').castToNumber;
  26. const geospatial = require('./operators/geospatial');
  27. const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue;
  28. let MongooseArray;
  29. let EmbeddedDoc;
  30. /**
  31. * Array SchemaType constructor
  32. *
  33. * @param {String} key
  34. * @param {SchemaType} cast
  35. * @param {Object} options
  36. * @inherits SchemaType
  37. * @api public
  38. */
  39. function SchemaArray(key, cast, options, schemaOptions) {
  40. // lazy load
  41. EmbeddedDoc || (EmbeddedDoc = require('../types').Embedded);
  42. let typeKey = 'type';
  43. if (schemaOptions && schemaOptions.typeKey) {
  44. typeKey = schemaOptions.typeKey;
  45. }
  46. if (cast) {
  47. let castOptions = {};
  48. if (utils.getFunctionName(cast.constructor) === 'Object') {
  49. if (cast[typeKey]) {
  50. // support { type: Woot }
  51. castOptions = utils.clone(cast); // do not alter user arguments
  52. delete castOptions[typeKey];
  53. cast = cast[typeKey];
  54. } else {
  55. cast = Mixed;
  56. }
  57. }
  58. if (cast === Object) {
  59. cast = Mixed;
  60. }
  61. // support { type: 'String' }
  62. const name = typeof cast === 'string'
  63. ? cast
  64. : utils.getFunctionName(cast);
  65. const caster = name in Types
  66. ? Types[name]
  67. : cast;
  68. this.casterConstructor = caster;
  69. if (typeof caster === 'function' &&
  70. !caster.$isArraySubdocument &&
  71. !caster.$isSchemaMap) {
  72. this.caster = new caster(null, castOptions);
  73. } else {
  74. this.caster = caster;
  75. }
  76. if (!(this.caster instanceof EmbeddedDoc)) {
  77. this.caster.path = key;
  78. }
  79. }
  80. this.$isMongooseArray = true;
  81. SchemaType.call(this, key, options, 'Array');
  82. let defaultArr;
  83. let fn;
  84. if (this.defaultValue != null) {
  85. defaultArr = this.defaultValue;
  86. fn = typeof defaultArr === 'function';
  87. }
  88. if (!('defaultValue' in this) || this.defaultValue !== void 0) {
  89. const defaultFn = function() {
  90. let arr = [];
  91. if (fn) {
  92. arr = defaultArr.call(this);
  93. } else if (defaultArr != null) {
  94. arr = arr.concat(defaultArr);
  95. }
  96. // Leave it up to `cast()` to convert the array
  97. return arr;
  98. };
  99. defaultFn.$runBeforeSetters = true;
  100. this.default(defaultFn);
  101. }
  102. }
  103. /**
  104. * This schema type's name, to defend against minifiers that mangle
  105. * function names.
  106. *
  107. * @api public
  108. */
  109. SchemaArray.schemaName = 'Array';
  110. /*!
  111. * Inherits from SchemaType.
  112. */
  113. SchemaArray.prototype = Object.create(SchemaType.prototype);
  114. SchemaArray.prototype.constructor = SchemaArray;
  115. /**
  116. * Adds an enum validator if this is an array of strings. Equivalent to
  117. * `SchemaString.prototype.enum()`
  118. *
  119. * @param {String|Object} [args...] enumeration values
  120. * @return {SchemaType} this
  121. */
  122. SchemaArray.prototype.enum = function() {
  123. const instance = get(this, 'caster.instance');
  124. if (instance !== 'String') {
  125. throw new Error('`enum` can only be set on an array of strings, not ' + instance);
  126. }
  127. this.caster.enum.apply(this.caster, arguments);
  128. return this;
  129. };
  130. /**
  131. * Overrides the getters application for the population special-case
  132. *
  133. * @param {Object} value
  134. * @param {Object} scope
  135. * @api private
  136. */
  137. SchemaArray.prototype.applyGetters = function(value, scope) {
  138. if (this.caster.options && this.caster.options.ref) {
  139. // means the object id was populated
  140. return value;
  141. }
  142. return SchemaType.prototype.applyGetters.call(this, value, scope);
  143. };
  144. /**
  145. * Casts values for set().
  146. *
  147. * @param {Object} value
  148. * @param {Document} doc document that triggers the casting
  149. * @param {Boolean} init whether this is an initialization cast
  150. * @api private
  151. */
  152. SchemaArray.prototype.cast = function(value, doc, init) {
  153. // lazy load
  154. MongooseArray || (MongooseArray = require('../types').Array);
  155. let i;
  156. let l;
  157. if (Array.isArray(value)) {
  158. if (!value.length && doc) {
  159. const indexes = doc.schema.indexedPaths();
  160. for (i = 0, l = indexes.length; i < l; ++i) {
  161. const pathIndex = indexes[i][0][this.path];
  162. if (pathIndex === '2dsphere' || pathIndex === '2d') {
  163. return;
  164. }
  165. }
  166. }
  167. if (!(value && value.isMongooseArray)) {
  168. value = new MongooseArray(value, this.path, doc);
  169. } else if (value && value.isMongooseArray) {
  170. // We need to create a new array, otherwise change tracking will
  171. // update the old doc (gh-4449)
  172. value = new MongooseArray(value, this.path, doc);
  173. }
  174. if (this.caster && this.casterConstructor !== Mixed) {
  175. try {
  176. for (i = 0, l = value.length; i < l; i++) {
  177. value[i] = this.caster.cast(value[i], doc, init);
  178. }
  179. } catch (e) {
  180. // rethrow
  181. throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e);
  182. }
  183. }
  184. return value;
  185. }
  186. // gh-2442: if we're loading this from the db and its not an array, mark
  187. // the whole array as modified.
  188. if (!!doc && !!init) {
  189. doc.markModified(this.path);
  190. }
  191. return this.cast([value], doc, init);
  192. };
  193. /*!
  194. * Ignore
  195. */
  196. SchemaArray.prototype.discriminator = function(name, schema) {
  197. let arr = this; // eslint-disable-line consistent-this
  198. while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) {
  199. arr = arr.casterConstructor;
  200. if (arr == null || typeof arr === 'function') {
  201. throw new MongooseError('You can only add an embedded discriminator on ' +
  202. 'a document array, ' + this.path + ' is a plain array');
  203. }
  204. }
  205. return arr.discriminator(name, schema);
  206. };
  207. /**
  208. * Casts values for queries.
  209. *
  210. * @param {String} $conditional
  211. * @param {any} [value]
  212. * @api private
  213. */
  214. SchemaArray.prototype.castForQuery = function($conditional, value) {
  215. let handler;
  216. let val;
  217. if (arguments.length === 2) {
  218. handler = this.$conditionalHandlers[$conditional];
  219. if (!handler) {
  220. throw new Error('Can\'t use ' + $conditional + ' with Array.');
  221. }
  222. val = handler.call(this, value);
  223. } else {
  224. val = $conditional;
  225. let Constructor = this.casterConstructor;
  226. if (val &&
  227. Constructor.discriminators &&
  228. Constructor.schema &&
  229. Constructor.schema.options &&
  230. Constructor.schema.options.discriminatorKey) {
  231. if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' &&
  232. Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
  233. Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
  234. } else {
  235. const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]);
  236. if (constructorByValue) {
  237. Constructor = constructorByValue;
  238. }
  239. }
  240. }
  241. const proto = this.casterConstructor.prototype;
  242. let method = proto && (proto.castForQuery || proto.cast);
  243. if (!method && Constructor.castForQuery) {
  244. method = Constructor.castForQuery;
  245. }
  246. const caster = this.caster;
  247. if (Array.isArray(val)) {
  248. this.setters.reverse().forEach(setter => {
  249. val = setter.call(this, val, this);
  250. });
  251. val = val.map(function(v) {
  252. if (utils.isObject(v) && v.$elemMatch) {
  253. return v;
  254. }
  255. if (method) {
  256. v = method.call(caster, v);
  257. return v;
  258. }
  259. if (v != null) {
  260. v = new Constructor(v);
  261. return v;
  262. }
  263. return v;
  264. });
  265. } else if (method) {
  266. val = method.call(caster, val);
  267. } else if (val != null) {
  268. val = new Constructor(val);
  269. }
  270. }
  271. return val;
  272. };
  273. function cast$all(val) {
  274. if (!Array.isArray(val)) {
  275. val = [val];
  276. }
  277. val = val.map(function(v) {
  278. if (utils.isObject(v)) {
  279. const o = {};
  280. o[this.path] = v;
  281. return cast(this.casterConstructor.schema, o)[this.path];
  282. }
  283. return v;
  284. }, this);
  285. return this.castForQuery(val);
  286. }
  287. function cast$elemMatch(val) {
  288. const keys = Object.keys(val);
  289. const numKeys = keys.length;
  290. let key;
  291. let value;
  292. for (let i = 0; i < numKeys; ++i) {
  293. key = keys[i];
  294. value = val[key];
  295. if (key.indexOf('$') === 0 && value) {
  296. val[key] = this.castForQuery(key, value);
  297. }
  298. }
  299. return cast(this.casterConstructor.schema, val);
  300. }
  301. const handle = SchemaArray.prototype.$conditionalHandlers = {};
  302. handle.$all = cast$all;
  303. handle.$options = String;
  304. handle.$elemMatch = cast$elemMatch;
  305. handle.$geoIntersects = geospatial.cast$geoIntersects;
  306. handle.$or = handle.$and = function(val) {
  307. if (!Array.isArray(val)) {
  308. throw new TypeError('conditional $or/$and require array');
  309. }
  310. const ret = [];
  311. for (let i = 0; i < val.length; ++i) {
  312. ret.push(cast(this.casterConstructor.schema, val[i]));
  313. }
  314. return ret;
  315. };
  316. handle.$near =
  317. handle.$nearSphere = geospatial.cast$near;
  318. handle.$within =
  319. handle.$geoWithin = geospatial.cast$within;
  320. handle.$size =
  321. handle.$minDistance =
  322. handle.$maxDistance = castToNumber;
  323. handle.$exists = $exists;
  324. handle.$type = $type;
  325. handle.$eq =
  326. handle.$gt =
  327. handle.$gte =
  328. handle.$lt =
  329. handle.$lte =
  330. handle.$ne =
  331. handle.$nin =
  332. handle.$regex = SchemaArray.prototype.castForQuery;
  333. // `$in` is special because you can also include an empty array in the query
  334. // like `$in: [1, []]`, see gh-5913
  335. handle.$in = SchemaType.prototype.$conditionalHandlers.$in;
  336. /*!
  337. * Module exports.
  338. */
  339. module.exports = SchemaArray;