array.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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.isPOJO(cast)) {
  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. * Options for all arrays.
  112. *
  113. * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting.
  114. *
  115. * @static options
  116. * @api public
  117. */
  118. SchemaArray.options = { castNonArrays: true };
  119. /*!
  120. * Inherits from SchemaType.
  121. */
  122. SchemaArray.prototype = Object.create(SchemaType.prototype);
  123. SchemaArray.prototype.constructor = SchemaArray;
  124. /**
  125. * Adds an enum validator if this is an array of strings. Equivalent to
  126. * `SchemaString.prototype.enum()`
  127. *
  128. * @param {String|Object} [args...] enumeration values
  129. * @return {SchemaType} this
  130. */
  131. SchemaArray.prototype.enum = function() {
  132. const instance = get(this, 'caster.instance');
  133. if (instance !== 'String') {
  134. throw new Error('`enum` can only be set on an array of strings, not ' + instance);
  135. }
  136. this.caster.enum.apply(this.caster, arguments);
  137. return this;
  138. };
  139. /**
  140. * Overrides the getters application for the population special-case
  141. *
  142. * @param {Object} value
  143. * @param {Object} scope
  144. * @api private
  145. */
  146. SchemaArray.prototype.applyGetters = function(value, scope) {
  147. if (this.caster.options && this.caster.options.ref) {
  148. // means the object id was populated
  149. return value;
  150. }
  151. return SchemaType.prototype.applyGetters.call(this, value, scope);
  152. };
  153. /**
  154. * Casts values for set().
  155. *
  156. * @param {Object} value
  157. * @param {Document} doc document that triggers the casting
  158. * @param {Boolean} init whether this is an initialization cast
  159. * @api private
  160. */
  161. SchemaArray.prototype.cast = function(value, doc, init) {
  162. // lazy load
  163. MongooseArray || (MongooseArray = require('../types').Array);
  164. let i;
  165. let l;
  166. if (Array.isArray(value)) {
  167. if (!value.length && doc) {
  168. const indexes = doc.schema.indexedPaths();
  169. for (i = 0, l = indexes.length; i < l; ++i) {
  170. const pathIndex = indexes[i][0][this.path];
  171. if (pathIndex === '2dsphere' || pathIndex === '2d') {
  172. return;
  173. }
  174. }
  175. }
  176. if (!(value && value.isMongooseArray)) {
  177. value = new MongooseArray(value, this.path, doc);
  178. } else if (value && value.isMongooseArray) {
  179. // We need to create a new array, otherwise change tracking will
  180. // update the old doc (gh-4449)
  181. value = new MongooseArray(value, this.path, doc);
  182. }
  183. if (this.caster && this.casterConstructor !== Mixed) {
  184. try {
  185. for (i = 0, l = value.length; i < l; i++) {
  186. value[i] = this.caster.cast(value[i], doc, init);
  187. }
  188. } catch (e) {
  189. // rethrow
  190. throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e);
  191. }
  192. }
  193. return value;
  194. }
  195. if (init || SchemaArray.options.castNonArrays) {
  196. // gh-2442: if we're loading this from the db and its not an array, mark
  197. // the whole array as modified.
  198. if (!!doc && !!init) {
  199. doc.markModified(this.path);
  200. }
  201. return this.cast([value], doc, init);
  202. }
  203. throw new CastError('Array', util.inspect(value), this.path);
  204. };
  205. /*!
  206. * Ignore
  207. */
  208. SchemaArray.prototype.discriminator = function(name, schema) {
  209. let arr = this; // eslint-disable-line consistent-this
  210. while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) {
  211. arr = arr.casterConstructor;
  212. if (arr == null || typeof arr === 'function') {
  213. throw new MongooseError('You can only add an embedded discriminator on ' +
  214. 'a document array, ' + this.path + ' is a plain array');
  215. }
  216. }
  217. return arr.discriminator(name, schema);
  218. };
  219. /**
  220. * Casts values for queries.
  221. *
  222. * @param {String} $conditional
  223. * @param {any} [value]
  224. * @api private
  225. */
  226. SchemaArray.prototype.castForQuery = function($conditional, value) {
  227. let handler;
  228. let val;
  229. if (arguments.length === 2) {
  230. handler = this.$conditionalHandlers[$conditional];
  231. if (!handler) {
  232. throw new Error('Can\'t use ' + $conditional + ' with Array.');
  233. }
  234. val = handler.call(this, value);
  235. } else {
  236. val = $conditional;
  237. let Constructor = this.casterConstructor;
  238. if (val &&
  239. Constructor.discriminators &&
  240. Constructor.schema &&
  241. Constructor.schema.options &&
  242. Constructor.schema.options.discriminatorKey) {
  243. if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' &&
  244. Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
  245. Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
  246. } else {
  247. const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]);
  248. if (constructorByValue) {
  249. Constructor = constructorByValue;
  250. }
  251. }
  252. }
  253. const proto = this.casterConstructor.prototype;
  254. let method = proto && (proto.castForQuery || proto.cast);
  255. if (!method && Constructor.castForQuery) {
  256. method = Constructor.castForQuery;
  257. }
  258. const caster = this.caster;
  259. if (Array.isArray(val)) {
  260. this.setters.reverse().forEach(setter => {
  261. val = setter.call(this, val, this);
  262. });
  263. val = val.map(function(v) {
  264. if (utils.isObject(v) && v.$elemMatch) {
  265. return v;
  266. }
  267. if (method) {
  268. v = method.call(caster, v);
  269. return v;
  270. }
  271. if (v != null) {
  272. v = new Constructor(v);
  273. return v;
  274. }
  275. return v;
  276. });
  277. } else if (method) {
  278. val = method.call(caster, val);
  279. } else if (val != null) {
  280. val = new Constructor(val);
  281. }
  282. }
  283. return val;
  284. };
  285. function cast$all(val) {
  286. if (!Array.isArray(val)) {
  287. val = [val];
  288. }
  289. val = val.map(function(v) {
  290. if (utils.isObject(v)) {
  291. const o = {};
  292. o[this.path] = v;
  293. return cast(this.casterConstructor.schema, o)[this.path];
  294. }
  295. return v;
  296. }, this);
  297. return this.castForQuery(val);
  298. }
  299. function cast$elemMatch(val) {
  300. const keys = Object.keys(val);
  301. const numKeys = keys.length;
  302. for (let i = 0; i < numKeys; ++i) {
  303. const key = keys[i];
  304. const value = val[key];
  305. if (key.indexOf('$') === 0 && value) {
  306. val[key] = this.castForQuery(key, value);
  307. }
  308. }
  309. // Is this an embedded discriminator and is the discriminator key set?
  310. // If so, use the discriminator schema. See gh-7449
  311. const discriminatorKey = get(this,
  312. 'casterConstructor.schema.options.discriminatorKey');
  313. const discriminators = get(this, 'casterConstructor.schema.discriminators', {});
  314. if (discriminatorKey != null &&
  315. val[discriminatorKey] != null &&
  316. discriminators[val[discriminatorKey]] != null) {
  317. return cast(discriminators[val[discriminatorKey]], val);
  318. }
  319. return cast(this.casterConstructor.schema, val);
  320. }
  321. const handle = SchemaArray.prototype.$conditionalHandlers = {};
  322. handle.$all = cast$all;
  323. handle.$options = String;
  324. handle.$elemMatch = cast$elemMatch;
  325. handle.$geoIntersects = geospatial.cast$geoIntersects;
  326. handle.$or = handle.$and = function(val) {
  327. if (!Array.isArray(val)) {
  328. throw new TypeError('conditional $or/$and require array');
  329. }
  330. const ret = [];
  331. for (let i = 0; i < val.length; ++i) {
  332. ret.push(cast(this.casterConstructor.schema, val[i]));
  333. }
  334. return ret;
  335. };
  336. handle.$near =
  337. handle.$nearSphere = geospatial.cast$near;
  338. handle.$within =
  339. handle.$geoWithin = geospatial.cast$within;
  340. handle.$size =
  341. handle.$minDistance =
  342. handle.$maxDistance = castToNumber;
  343. handle.$exists = $exists;
  344. handle.$type = $type;
  345. handle.$eq =
  346. handle.$gt =
  347. handle.$gte =
  348. handle.$lt =
  349. handle.$lte =
  350. handle.$ne =
  351. handle.$nin =
  352. handle.$regex = SchemaArray.prototype.castForQuery;
  353. // `$in` is special because you can also include an empty array in the query
  354. // like `$in: [1, []]`, see gh-5913
  355. handle.$in = SchemaType.prototype.$conditionalHandlers.$in;
  356. /*!
  357. * Module exports.
  358. */
  359. module.exports = SchemaArray;