array.js 8.5 KB

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