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.

305 lines
6.8 KiB

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