array.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*!
  2. * Module dependencies.
  3. */
  4. var SchemaType = require('../schematype');
  5. var CastError = SchemaType.CastError;
  6. var Types = {
  7. Boolean: require('./boolean'),
  8. Date: require('./date'),
  9. Number: require('./number'),
  10. String: require('./string'),
  11. ObjectId: require('./objectid'),
  12. Buffer: require('./buffer')
  13. };
  14. var MongooseArray = require('../types').Array;
  15. var EmbeddedDoc = require('../types').Embedded;
  16. var Mixed = require('./mixed');
  17. var cast = require('../cast');
  18. var util = require('util');
  19. var utils = require('../utils');
  20. var castToNumber = require('./operators/helpers').castToNumber;
  21. var geospatial = require('./operators/geospatial');
  22. /**
  23. * Array SchemaType constructor
  24. *
  25. * @param {String} key
  26. * @param {SchemaType} cast
  27. * @param {Object} options
  28. * @inherits SchemaType
  29. * @api public
  30. */
  31. function SchemaArray(key, cast, options, schemaOptions) {
  32. var typeKey = 'type';
  33. if (schemaOptions && schemaOptions.typeKey) {
  34. typeKey = schemaOptions.typeKey;
  35. }
  36. if (cast) {
  37. var castOptions = {};
  38. if (utils.getFunctionName(cast.constructor) === 'Object') {
  39. if (cast[typeKey]) {
  40. // support { type: Woot }
  41. castOptions = utils.clone(cast); // do not alter user arguments
  42. delete castOptions[typeKey];
  43. cast = cast[typeKey];
  44. } else {
  45. cast = Mixed;
  46. }
  47. }
  48. // support { type: 'String' }
  49. var name = typeof cast === 'string'
  50. ? cast
  51. : utils.getFunctionName(cast);
  52. var caster = name in Types
  53. ? Types[name]
  54. : cast;
  55. this.casterConstructor = caster;
  56. if (typeof caster === 'function') {
  57. this.caster = new caster(null, castOptions);
  58. } else {
  59. this.caster = caster;
  60. }
  61. if (!(this.caster instanceof EmbeddedDoc)) {
  62. this.caster.path = key;
  63. }
  64. }
  65. SchemaType.call(this, key, options, 'Array');
  66. var defaultArr;
  67. var fn;
  68. if (this.defaultValue != null) {
  69. defaultArr = this.defaultValue;
  70. fn = typeof defaultArr === 'function';
  71. }
  72. if (!('defaultValue' in this) || this.defaultValue !== void 0) {
  73. this.default(function() {
  74. var arr = [];
  75. if (fn) {
  76. arr = defaultArr();
  77. } else if (defaultArr != null) {
  78. arr = defaultArr;
  79. }
  80. // Leave it up to `cast()` to convert the array
  81. return arr;
  82. });
  83. }
  84. }
  85. /**
  86. * This schema type's name, to defend against minifiers that mangle
  87. * function names.
  88. *
  89. * @api public
  90. */
  91. SchemaArray.schemaName = 'Array';
  92. /*!
  93. * Inherits from SchemaType.
  94. */
  95. SchemaArray.prototype = Object.create(SchemaType.prototype);
  96. SchemaArray.prototype.constructor = SchemaArray;
  97. /**
  98. * Check if the given value satisfies a required validator. The given value
  99. * must be not null nor undefined, and have a non-zero length.
  100. *
  101. * @param {Any} value
  102. * @return {Boolean}
  103. * @api public
  104. */
  105. SchemaArray.prototype.checkRequired = function(value) {
  106. return !!(value && value.length);
  107. };
  108. /**
  109. * Overrides the getters application for the population special-case
  110. *
  111. * @param {Object} value
  112. * @param {Object} scope
  113. * @api private
  114. */
  115. SchemaArray.prototype.applyGetters = function(value, scope) {
  116. if (this.caster.options && this.caster.options.ref) {
  117. // means the object id was populated
  118. return value;
  119. }
  120. return SchemaType.prototype.applyGetters.call(this, value, scope);
  121. };
  122. /**
  123. * Casts values for set().
  124. *
  125. * @param {Object} value
  126. * @param {Document} doc document that triggers the casting
  127. * @param {Boolean} init whether this is an initialization cast
  128. * @api private
  129. */
  130. SchemaArray.prototype.cast = function(value, doc, init) {
  131. if (Array.isArray(value)) {
  132. if (!value.length && doc) {
  133. var indexes = doc.schema.indexedPaths();
  134. for (var i = 0, l = indexes.length; i < l; ++i) {
  135. var pathIndex = indexes[i][0][this.path];
  136. if (pathIndex === '2dsphere' || pathIndex === '2d') {
  137. return;
  138. }
  139. }
  140. }
  141. if (!(value && value.isMongooseArray)) {
  142. value = new MongooseArray(value, this.path, doc);
  143. } else if (value && value.isMongooseArray) {
  144. // We need to create a new array, otherwise change tracking will
  145. // update the old doc (gh-4449)
  146. value = new MongooseArray(value, this.path, doc);
  147. }
  148. if (this.caster) {
  149. try {
  150. for (i = 0, l = value.length; i < l; i++) {
  151. value[i] = this.caster.cast(value[i], doc, init);
  152. }
  153. } catch (e) {
  154. // rethrow
  155. throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e);
  156. }
  157. }
  158. return value;
  159. }
  160. // gh-2442: if we're loading this from the db and its not an array, mark
  161. // the whole array as modified.
  162. if (!!doc && !!init) {
  163. doc.markModified(this.path);
  164. }
  165. return this.cast([value], doc, init);
  166. };
  167. /**
  168. * Casts values for queries.
  169. *
  170. * @param {String} $conditional
  171. * @param {any} [value]
  172. * @api private
  173. */
  174. SchemaArray.prototype.castForQuery = function($conditional, value) {
  175. var handler,
  176. val;
  177. if (arguments.length === 2) {
  178. handler = this.$conditionalHandlers[$conditional];
  179. if (!handler) {
  180. throw new Error('Can\'t use ' + $conditional + ' with Array.');
  181. }
  182. val = handler.call(this, value);
  183. } else {
  184. val = $conditional;
  185. var proto = this.casterConstructor.prototype;
  186. var method = proto && (proto.castForQuery || proto.cast);
  187. var caster = this.caster;
  188. if (Array.isArray(val)) {
  189. val = val.map(function(v) {
  190. if (utils.isObject(v) && v.$elemMatch) {
  191. return v;
  192. }
  193. if (method) {
  194. v = method.call(caster, v);
  195. }
  196. return v;
  197. });
  198. } else if (method) {
  199. val = method.call(caster, val);
  200. }
  201. }
  202. return val;
  203. };
  204. function cast$all(val) {
  205. if (!Array.isArray(val)) {
  206. val = [val];
  207. }
  208. val = val.map(function(v) {
  209. if (utils.isObject(v)) {
  210. var o = {};
  211. o[this.path] = v;
  212. return cast(this.casterConstructor.schema, o)[this.path];
  213. }
  214. return v;
  215. }, this);
  216. return this.castForQuery(val);
  217. }
  218. function cast$elemMatch(val) {
  219. var keys = Object.keys(val);
  220. var numKeys = keys.length;
  221. var key;
  222. var value;
  223. for (var i = 0; i < numKeys; ++i) {
  224. key = keys[i];
  225. value = val[key];
  226. if (key.indexOf('$') === 0 && value) {
  227. val[key] = this.castForQuery(key, value);
  228. }
  229. }
  230. return cast(this.casterConstructor.schema, val);
  231. }
  232. var handle = SchemaArray.prototype.$conditionalHandlers = {};
  233. handle.$all = cast$all;
  234. handle.$options = String;
  235. handle.$elemMatch = cast$elemMatch;
  236. handle.$geoIntersects = geospatial.cast$geoIntersects;
  237. handle.$or = handle.$and = function(val) {
  238. if (!Array.isArray(val)) {
  239. throw new TypeError('conditional $or/$and require array');
  240. }
  241. var ret = [];
  242. for (var i = 0; i < val.length; ++i) {
  243. ret.push(cast(this.casterConstructor.schema, val[i]));
  244. }
  245. return ret;
  246. };
  247. handle.$near =
  248. handle.$nearSphere = geospatial.cast$near;
  249. handle.$within =
  250. handle.$geoWithin = geospatial.cast$within;
  251. handle.$size =
  252. handle.$minDistance =
  253. handle.$maxDistance = castToNumber;
  254. handle.$eq =
  255. handle.$gt =
  256. handle.$gte =
  257. handle.$in =
  258. handle.$lt =
  259. handle.$lte =
  260. handle.$ne =
  261. handle.$nin =
  262. handle.$regex = SchemaArray.prototype.castForQuery;
  263. /*!
  264. * Module exports.
  265. */
  266. module.exports = SchemaArray;