number.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. 'use strict';
  2. /*!
  3. * Module requirements.
  4. */
  5. const MongooseError = require('../error/index');
  6. const SchemaNumberOptions = require('../options/SchemaNumberOptions');
  7. const SchemaType = require('../schematype');
  8. const castNumber = require('../cast/number');
  9. const handleBitwiseOperator = require('./operators/bitwise');
  10. const utils = require('../utils');
  11. const CastError = SchemaType.CastError;
  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. * Sets a default option for all Number instances.
  43. *
  44. * ####Example:
  45. *
  46. * // Make all numbers have option `min` equal to 0.
  47. * mongoose.Schema.Number.set('min', 0);
  48. *
  49. * const Order = mongoose.model('Order', new Schema({ amount: Number }));
  50. * new Order({ amount: -10 }).validateSync().errors.amount.message; // Path `amount` must be larger than 0.
  51. *
  52. * @param {String} option - The option you'd like to set the value for
  53. * @param {*} value - value for option
  54. * @return {undefined}
  55. * @function set
  56. * @static
  57. * @api public
  58. */
  59. SchemaNumber.set = SchemaType.set;
  60. /*!
  61. * ignore
  62. */
  63. SchemaNumber._cast = castNumber;
  64. /**
  65. * Get/set the function used to cast arbitrary values to numbers.
  66. *
  67. * ####Example:
  68. *
  69. * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers
  70. * const original = mongoose.Number.cast();
  71. * mongoose.Number.cast(v => {
  72. * if (v === '') { return 0; }
  73. * return original(v);
  74. * });
  75. *
  76. * // Or disable casting entirely
  77. * mongoose.Number.cast(false);
  78. *
  79. * @param {Function} caster
  80. * @return {Function}
  81. * @function get
  82. * @static
  83. * @api public
  84. */
  85. SchemaNumber.cast = function cast(caster) {
  86. if (arguments.length === 0) {
  87. return this._cast;
  88. }
  89. if (caster === false) {
  90. caster = this._defaultCaster;
  91. }
  92. this._cast = caster;
  93. return this._cast;
  94. };
  95. /*!
  96. * ignore
  97. */
  98. SchemaNumber._defaultCaster = v => {
  99. if (typeof v !== 'number') {
  100. throw new Error();
  101. }
  102. return v;
  103. };
  104. /**
  105. * This schema type's name, to defend against minifiers that mangle
  106. * function names.
  107. *
  108. * @api public
  109. */
  110. SchemaNumber.schemaName = 'Number';
  111. SchemaNumber.defaultOptions = {};
  112. /*!
  113. * Inherits from SchemaType.
  114. */
  115. SchemaNumber.prototype = Object.create(SchemaType.prototype);
  116. SchemaNumber.prototype.constructor = SchemaNumber;
  117. SchemaNumber.prototype.OptionsConstructor = SchemaNumberOptions;
  118. /*!
  119. * ignore
  120. */
  121. SchemaNumber._checkRequired = v => typeof v === 'number' || v instanceof Number;
  122. /**
  123. * Override the function the required validator uses to check whether a string
  124. * passes the `required` check.
  125. *
  126. * @param {Function} fn
  127. * @return {Function}
  128. * @function checkRequired
  129. * @static
  130. * @api public
  131. */
  132. SchemaNumber.checkRequired = SchemaType.checkRequired;
  133. /**
  134. * Check if the given value satisfies a required validator.
  135. *
  136. * @param {Any} value
  137. * @param {Document} doc
  138. * @return {Boolean}
  139. * @api public
  140. */
  141. SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
  142. if (SchemaType._isRef(this, value, doc, true)) {
  143. return !!value;
  144. }
  145. // `require('util').inherits()` does **not** copy static properties, and
  146. // plugins like mongoose-float use `inherits()` for pre-ES6.
  147. const _checkRequired = typeof this.constructor.checkRequired == 'function' ?
  148. this.constructor.checkRequired() :
  149. SchemaNumber.checkRequired();
  150. return _checkRequired(value);
  151. };
  152. /**
  153. * Sets a minimum number validator.
  154. *
  155. * ####Example:
  156. *
  157. * const s = new Schema({ n: { type: Number, min: 10 })
  158. * const M = db.model('M', s)
  159. * const m = new M({ n: 9 })
  160. * m.save(function (err) {
  161. * console.error(err) // validator error
  162. * m.n = 10;
  163. * m.save() // success
  164. * })
  165. *
  166. * // custom error messages
  167. * // We can also use the special {MIN} token which will be replaced with the invalid value
  168. * const min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
  169. * const schema = new Schema({ n: { type: Number, min: min })
  170. * const M = mongoose.model('Measurement', schema);
  171. * const s= new M({ n: 4 });
  172. * s.validate(function (err) {
  173. * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
  174. * })
  175. *
  176. * @param {Number} value minimum number
  177. * @param {String} [message] optional custom error message
  178. * @return {SchemaType} this
  179. * @see Customized Error Messages #error_messages_MongooseError-messages
  180. * @api public
  181. */
  182. SchemaNumber.prototype.min = function(value, message) {
  183. if (this.minValidator) {
  184. this.validators = this.validators.filter(function(v) {
  185. return v.validator !== this.minValidator;
  186. }, this);
  187. }
  188. if (value !== null && value !== undefined) {
  189. let msg = message || MongooseError.messages.Number.min;
  190. msg = msg.replace(/{MIN}/, value);
  191. this.validators.push({
  192. validator: this.minValidator = function(v) {
  193. return v == null || v >= value;
  194. },
  195. message: msg,
  196. type: 'min',
  197. min: value
  198. });
  199. }
  200. return this;
  201. };
  202. /**
  203. * Sets a maximum number validator.
  204. *
  205. * ####Example:
  206. *
  207. * const s = new Schema({ n: { type: Number, max: 10 })
  208. * const M = db.model('M', s)
  209. * const m = new M({ n: 11 })
  210. * m.save(function (err) {
  211. * console.error(err) // validator error
  212. * m.n = 10;
  213. * m.save() // success
  214. * })
  215. *
  216. * // custom error messages
  217. * // We can also use the special {MAX} token which will be replaced with the invalid value
  218. * const max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
  219. * const schema = new Schema({ n: { type: Number, max: max })
  220. * const M = mongoose.model('Measurement', schema);
  221. * const s= new M({ n: 4 });
  222. * s.validate(function (err) {
  223. * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
  224. * })
  225. *
  226. * @param {Number} maximum number
  227. * @param {String} [message] optional custom error message
  228. * @return {SchemaType} this
  229. * @see Customized Error Messages #error_messages_MongooseError-messages
  230. * @api public
  231. */
  232. SchemaNumber.prototype.max = function(value, message) {
  233. if (this.maxValidator) {
  234. this.validators = this.validators.filter(function(v) {
  235. return v.validator !== this.maxValidator;
  236. }, this);
  237. }
  238. if (value !== null && value !== undefined) {
  239. let msg = message || MongooseError.messages.Number.max;
  240. msg = msg.replace(/{MAX}/, value);
  241. this.validators.push({
  242. validator: this.maxValidator = function(v) {
  243. return v == null || v <= value;
  244. },
  245. message: msg,
  246. type: 'max',
  247. max: value
  248. });
  249. }
  250. return this;
  251. };
  252. /**
  253. * Sets a enum validator
  254. *
  255. * ####Example:
  256. *
  257. * const s = new Schema({ n: { type: Number, enum: [1, 2, 3] });
  258. * const M = db.model('M', s);
  259. *
  260. * const m = new M({ n: 4 });
  261. * await m.save(); // throws validation error
  262. *
  263. * m.n = 3;
  264. * await m.save(); // succeeds
  265. *
  266. * @param {Array} values allowed values
  267. * @param {String} [message] optional custom error message
  268. * @return {SchemaType} this
  269. * @see Customized Error Messages #error_messages_MongooseError-messages
  270. * @api public
  271. */
  272. SchemaNumber.prototype.enum = function(values, message) {
  273. if (this.enumValidator) {
  274. this.validators = this.validators.filter(function(v) {
  275. return v.validator !== this.enumValidator;
  276. }, this);
  277. }
  278. if (!Array.isArray(values)) {
  279. const isObjectSyntax = utils.isPOJO(values) && values.values != null;
  280. if (isObjectSyntax) {
  281. message = values.message;
  282. values = values.values;
  283. } else if (typeof values === 'number') {
  284. values = Array.prototype.slice.call(arguments);
  285. message = null;
  286. }
  287. if (utils.isPOJO(values)) {
  288. values = Object.values(values);
  289. }
  290. message = message || MongooseError.messages.Number.enum;
  291. }
  292. message = message == null ? MongooseError.messages.Number.enum : message;
  293. this.enumValidator = v => v == null || values.indexOf(v) !== -1;
  294. this.validators.push({
  295. validator: this.enumValidator,
  296. message: message,
  297. type: 'enum',
  298. enumValues: values
  299. });
  300. return this;
  301. };
  302. /**
  303. * Casts to number
  304. *
  305. * @param {Object} value value to cast
  306. * @param {Document} doc document that triggers the casting
  307. * @param {Boolean} init
  308. * @api private
  309. */
  310. SchemaNumber.prototype.cast = function(value, doc, init) {
  311. if (SchemaType._isRef(this, value, doc, init)) {
  312. if (typeof value === 'number') {
  313. return value;
  314. }
  315. if (value == null || utils.isNonBuiltinObject(value)) {
  316. return this._castRef(value, doc, init);
  317. }
  318. }
  319. const val = value && typeof value._id !== 'undefined' ?
  320. value._id : // documents
  321. value;
  322. let castNumber;
  323. if (typeof this._castFunction === 'function') {
  324. castNumber = this._castFunction;
  325. } else if (typeof this.constructor.cast === 'function') {
  326. castNumber = this.constructor.cast();
  327. } else {
  328. castNumber = SchemaNumber.cast();
  329. }
  330. try {
  331. return castNumber(val);
  332. } catch (err) {
  333. throw new CastError('Number', val, this.path, err, this);
  334. }
  335. };
  336. /*!
  337. * ignore
  338. */
  339. function handleSingle(val) {
  340. return this.cast(val);
  341. }
  342. function handleArray(val) {
  343. const _this = this;
  344. if (!Array.isArray(val)) {
  345. return [this.cast(val)];
  346. }
  347. return val.map(function(m) {
  348. return _this.cast(m);
  349. });
  350. }
  351. SchemaNumber.prototype.$conditionalHandlers =
  352. utils.options(SchemaType.prototype.$conditionalHandlers, {
  353. $bitsAllClear: handleBitwiseOperator,
  354. $bitsAnyClear: handleBitwiseOperator,
  355. $bitsAllSet: handleBitwiseOperator,
  356. $bitsAnySet: handleBitwiseOperator,
  357. $gt: handleSingle,
  358. $gte: handleSingle,
  359. $lt: handleSingle,
  360. $lte: handleSingle,
  361. $mod: handleArray
  362. });
  363. /**
  364. * Casts contents for queries.
  365. *
  366. * @param {String} $conditional
  367. * @param {any} [value]
  368. * @api private
  369. */
  370. SchemaNumber.prototype.castForQuery = function($conditional, val) {
  371. let handler;
  372. if (arguments.length === 2) {
  373. handler = this.$conditionalHandlers[$conditional];
  374. if (!handler) {
  375. throw new CastError('number', val, this.path, null, this);
  376. }
  377. return handler.call(this, val);
  378. }
  379. val = this._castForQuery($conditional);
  380. return val;
  381. };
  382. /*!
  383. * Module exports.
  384. */
  385. module.exports = SchemaNumber;