number.js 11 KB

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