number.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. 'use strict';
  2. /*!
  3. * Module requirements.
  4. */
  5. const MongooseError = require('../error');
  6. const SchemaType = require('../schematype');
  7. const castNumber = require('../cast/number');
  8. const handleBitwiseOperator = require('./operators/bitwise');
  9. const utils = require('../utils');
  10. const CastError = SchemaType.CastError;
  11. let Document;
  12. /**
  13. * Number SchemaType constructor.
  14. *
  15. * @param {String} key
  16. * @param {Object} options
  17. * @inherits SchemaType
  18. * @api public
  19. */
  20. function SchemaNumber(key, options) {
  21. SchemaType.call(this, key, options, 'Number');
  22. }
  23. /**
  24. * Attaches a getter for all Number instances.
  25. *
  26. * ####Example:
  27. *
  28. * // Make all numbers round down
  29. * mongoose.Number.get(function(v) { return Math.floor(v); });
  30. *
  31. * const Model = mongoose.model('Test', new Schema({ test: Number }));
  32. * new Model({ test: 3.14 }).test; // 3
  33. *
  34. * @param {Function} getter
  35. * @return {this}
  36. * @function get
  37. * @static
  38. * @api public
  39. */
  40. SchemaNumber.get = SchemaType.get;
  41. /*!
  42. * ignore
  43. */
  44. SchemaNumber._cast = castNumber;
  45. /**
  46. * Get/set the function used to cast arbitrary values to numbers.
  47. *
  48. * ####Example:
  49. *
  50. * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers
  51. * const original = mongoose.Number.cast();
  52. * mongoose.Number.cast(v => {
  53. * if (v === '') { return 0; }
  54. * return original(v);
  55. * });
  56. *
  57. * // Or disable casting entirely
  58. * mongoose.Number.cast(false);
  59. *
  60. * @param {Function} caster
  61. * @return {Function}
  62. * @function get
  63. * @static
  64. * @api public
  65. */
  66. SchemaNumber.cast = function cast(caster) {
  67. if (arguments.length === 0) {
  68. return this._cast;
  69. }
  70. if (caster === false) {
  71. caster = v => {
  72. if (typeof v !== 'number') {
  73. throw new Error();
  74. }
  75. return v;
  76. };
  77. }
  78. this._cast = caster;
  79. return this._cast;
  80. };
  81. /**
  82. * This schema type's name, to defend against minifiers that mangle
  83. * function names.
  84. *
  85. * @api public
  86. */
  87. SchemaNumber.schemaName = 'Number';
  88. /*!
  89. * Inherits from SchemaType.
  90. */
  91. SchemaNumber.prototype = Object.create(SchemaType.prototype);
  92. SchemaNumber.prototype.constructor = SchemaNumber;
  93. /*!
  94. * ignore
  95. */
  96. SchemaNumber._checkRequired = v => typeof v === 'number' || v instanceof Number;
  97. /**
  98. * Override the function the required validator uses to check whether a string
  99. * passes the `required` check.
  100. *
  101. * @param {Function} fn
  102. * @return {Function}
  103. * @function checkRequired
  104. * @static
  105. * @api public
  106. */
  107. SchemaNumber.checkRequired = SchemaType.checkRequired;
  108. /**
  109. * Check if the given value satisfies a required validator.
  110. *
  111. * @param {Any} value
  112. * @param {Document} doc
  113. * @return {Boolean}
  114. * @api public
  115. */
  116. SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
  117. if (SchemaType._isRef(this, value, doc, true)) {
  118. return !!value;
  119. }
  120. // `require('util').inherits()` does **not** copy static properties, and
  121. // plugins like mongoose-float use `inherits()` for pre-ES6.
  122. const _checkRequired = typeof this.constructor.checkRequired == 'function' ?
  123. this.constructor.checkRequired() :
  124. SchemaNumber.checkRequired();
  125. return _checkRequired(value);
  126. };
  127. /**
  128. * Sets a minimum number validator.
  129. *
  130. * ####Example:
  131. *
  132. * var s = new Schema({ n: { type: Number, min: 10 })
  133. * var M = db.model('M', s)
  134. * var m = new M({ n: 9 })
  135. * m.save(function (err) {
  136. * console.error(err) // validator error
  137. * m.n = 10;
  138. * m.save() // success
  139. * })
  140. *
  141. * // custom error messages
  142. * // We can also use the special {MIN} token which will be replaced with the invalid value
  143. * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
  144. * var schema = new Schema({ n: { type: Number, min: min })
  145. * var M = mongoose.model('Measurement', schema);
  146. * var s= new M({ n: 4 });
  147. * s.validate(function (err) {
  148. * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
  149. * })
  150. *
  151. * @param {Number} value minimum number
  152. * @param {String} [message] optional custom error message
  153. * @return {SchemaType} this
  154. * @see Customized Error Messages #error_messages_MongooseError-messages
  155. * @api public
  156. */
  157. SchemaNumber.prototype.min = function(value, message) {
  158. if (this.minValidator) {
  159. this.validators = this.validators.filter(function(v) {
  160. return v.validator !== this.minValidator;
  161. }, this);
  162. }
  163. if (value !== null && value !== undefined) {
  164. let msg = message || MongooseError.messages.Number.min;
  165. msg = msg.replace(/{MIN}/, value);
  166. this.validators.push({
  167. validator: this.minValidator = function(v) {
  168. return v == null || v >= value;
  169. },
  170. message: msg,
  171. type: 'min',
  172. min: value
  173. });
  174. }
  175. return this;
  176. };
  177. /**
  178. * Sets a maximum number validator.
  179. *
  180. * ####Example:
  181. *
  182. * var s = new Schema({ n: { type: Number, max: 10 })
  183. * var M = db.model('M', s)
  184. * var m = new M({ n: 11 })
  185. * m.save(function (err) {
  186. * console.error(err) // validator error
  187. * m.n = 10;
  188. * m.save() // success
  189. * })
  190. *
  191. * // custom error messages
  192. * // We can also use the special {MAX} token which will be replaced with the invalid value
  193. * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
  194. * var schema = new Schema({ n: { type: Number, max: max })
  195. * var M = mongoose.model('Measurement', schema);
  196. * var s= new M({ n: 4 });
  197. * s.validate(function (err) {
  198. * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
  199. * })
  200. *
  201. * @param {Number} maximum number
  202. * @param {String} [message] optional custom error message
  203. * @return {SchemaType} this
  204. * @see Customized Error Messages #error_messages_MongooseError-messages
  205. * @api public
  206. */
  207. SchemaNumber.prototype.max = function(value, message) {
  208. if (this.maxValidator) {
  209. this.validators = this.validators.filter(function(v) {
  210. return v.validator !== this.maxValidator;
  211. }, this);
  212. }
  213. if (value !== null && value !== undefined) {
  214. let msg = message || MongooseError.messages.Number.max;
  215. msg = msg.replace(/{MAX}/, value);
  216. this.validators.push({
  217. validator: this.maxValidator = function(v) {
  218. return v == null || v <= value;
  219. },
  220. message: msg,
  221. type: 'max',
  222. max: value
  223. });
  224. }
  225. return this;
  226. };
  227. /**
  228. * Casts to number
  229. *
  230. * @param {Object} value value to cast
  231. * @param {Document} doc document that triggers the casting
  232. * @param {Boolean} init
  233. * @api private
  234. */
  235. SchemaNumber.prototype.cast = function(value, doc, init) {
  236. if (SchemaType._isRef(this, value, doc, init)) {
  237. // wait! we may need to cast this to a document
  238. if (value === null || value === undefined) {
  239. return value;
  240. }
  241. // lazy load
  242. Document || (Document = require('./../document'));
  243. if (value instanceof Document) {
  244. value.$__.wasPopulated = true;
  245. return value;
  246. }
  247. // setting a populated path
  248. if (typeof value === 'number') {
  249. return value;
  250. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
  251. throw new CastError('number', value, this.path);
  252. }
  253. // Handle the case where user directly sets a populated
  254. // path to a plain object; cast to the Model used in
  255. // the population query.
  256. const path = doc.$__fullPath(this.path);
  257. const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
  258. const pop = owner.populated(path, true);
  259. const ret = new pop.options.model(value);
  260. ret.$__.wasPopulated = true;
  261. return ret;
  262. }
  263. const val = value && typeof value._id !== 'undefined' ?
  264. value._id : // documents
  265. value;
  266. const castNumber = typeof this.constructor.cast === 'function' ?
  267. this.constructor.cast() :
  268. SchemaNumber.cast();
  269. try {
  270. return castNumber(val);
  271. } catch (err) {
  272. throw new CastError('number', val, this.path);
  273. }
  274. };
  275. /*!
  276. * ignore
  277. */
  278. function handleSingle(val) {
  279. return this.cast(val);
  280. }
  281. function handleArray(val) {
  282. const _this = this;
  283. if (!Array.isArray(val)) {
  284. return [this.cast(val)];
  285. }
  286. return val.map(function(m) {
  287. return _this.cast(m);
  288. });
  289. }
  290. SchemaNumber.prototype.$conditionalHandlers =
  291. utils.options(SchemaType.prototype.$conditionalHandlers, {
  292. $bitsAllClear: handleBitwiseOperator,
  293. $bitsAnyClear: handleBitwiseOperator,
  294. $bitsAllSet: handleBitwiseOperator,
  295. $bitsAnySet: handleBitwiseOperator,
  296. $gt: handleSingle,
  297. $gte: handleSingle,
  298. $lt: handleSingle,
  299. $lte: handleSingle,
  300. $mod: handleArray
  301. });
  302. /**
  303. * Casts contents for queries.
  304. *
  305. * @param {String} $conditional
  306. * @param {any} [value]
  307. * @api private
  308. */
  309. SchemaNumber.prototype.castForQuery = function($conditional, val) {
  310. let handler;
  311. if (arguments.length === 2) {
  312. handler = this.$conditionalHandlers[$conditional];
  313. if (!handler) {
  314. throw new CastError('Can\'t use ' + $conditional + ' with Number.');
  315. }
  316. return handler.call(this, val);
  317. }
  318. val = this._castForQuery($conditional);
  319. return val;
  320. };
  321. /*!
  322. * Module exports.
  323. */
  324. module.exports = SchemaNumber;