Ohm-Management - Projektarbeit B-ME
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.

number.js 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. return this.constructor._checkRequired(value);
  121. };
  122. /**
  123. * Sets a minimum number validator.
  124. *
  125. * ####Example:
  126. *
  127. * var s = new Schema({ n: { type: Number, min: 10 })
  128. * var M = db.model('M', s)
  129. * var m = new M({ n: 9 })
  130. * m.save(function (err) {
  131. * console.error(err) // validator error
  132. * m.n = 10;
  133. * m.save() // success
  134. * })
  135. *
  136. * // custom error messages
  137. * // We can also use the special {MIN} token which will be replaced with the invalid value
  138. * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
  139. * var schema = new Schema({ n: { type: Number, min: min })
  140. * var M = mongoose.model('Measurement', schema);
  141. * var s= new M({ n: 4 });
  142. * s.validate(function (err) {
  143. * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
  144. * })
  145. *
  146. * @param {Number} value minimum number
  147. * @param {String} [message] optional custom error message
  148. * @return {SchemaType} this
  149. * @see Customized Error Messages #error_messages_MongooseError-messages
  150. * @api public
  151. */
  152. SchemaNumber.prototype.min = function(value, message) {
  153. if (this.minValidator) {
  154. this.validators = this.validators.filter(function(v) {
  155. return v.validator !== this.minValidator;
  156. }, this);
  157. }
  158. if (value !== null && value !== undefined) {
  159. let msg = message || MongooseError.messages.Number.min;
  160. msg = msg.replace(/{MIN}/, value);
  161. this.validators.push({
  162. validator: this.minValidator = function(v) {
  163. return v == null || v >= value;
  164. },
  165. message: msg,
  166. type: 'min',
  167. min: value
  168. });
  169. }
  170. return this;
  171. };
  172. /**
  173. * Sets a maximum number validator.
  174. *
  175. * ####Example:
  176. *
  177. * var s = new Schema({ n: { type: Number, max: 10 })
  178. * var M = db.model('M', s)
  179. * var m = new M({ n: 11 })
  180. * m.save(function (err) {
  181. * console.error(err) // validator error
  182. * m.n = 10;
  183. * m.save() // success
  184. * })
  185. *
  186. * // custom error messages
  187. * // We can also use the special {MAX} token which will be replaced with the invalid value
  188. * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
  189. * var schema = new Schema({ n: { type: Number, max: max })
  190. * var M = mongoose.model('Measurement', schema);
  191. * var s= new M({ n: 4 });
  192. * s.validate(function (err) {
  193. * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
  194. * })
  195. *
  196. * @param {Number} maximum number
  197. * @param {String} [message] optional custom error message
  198. * @return {SchemaType} this
  199. * @see Customized Error Messages #error_messages_MongooseError-messages
  200. * @api public
  201. */
  202. SchemaNumber.prototype.max = function(value, message) {
  203. if (this.maxValidator) {
  204. this.validators = this.validators.filter(function(v) {
  205. return v.validator !== this.maxValidator;
  206. }, this);
  207. }
  208. if (value !== null && value !== undefined) {
  209. let msg = message || MongooseError.messages.Number.max;
  210. msg = msg.replace(/{MAX}/, value);
  211. this.validators.push({
  212. validator: this.maxValidator = function(v) {
  213. return v == null || v <= value;
  214. },
  215. message: msg,
  216. type: 'max',
  217. max: value
  218. });
  219. }
  220. return this;
  221. };
  222. /**
  223. * Casts to number
  224. *
  225. * @param {Object} value value to cast
  226. * @param {Document} doc document that triggers the casting
  227. * @param {Boolean} init
  228. * @api private
  229. */
  230. SchemaNumber.prototype.cast = function(value, doc, init) {
  231. if (SchemaType._isRef(this, value, doc, init)) {
  232. // wait! we may need to cast this to a document
  233. if (value === null || value === undefined) {
  234. return value;
  235. }
  236. // lazy load
  237. Document || (Document = require('./../document'));
  238. if (value instanceof Document) {
  239. value.$__.wasPopulated = true;
  240. return value;
  241. }
  242. // setting a populated path
  243. if (typeof value === 'number') {
  244. return value;
  245. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
  246. throw new CastError('number', value, this.path);
  247. }
  248. // Handle the case where user directly sets a populated
  249. // path to a plain object; cast to the Model used in
  250. // the population query.
  251. const path = doc.$__fullPath(this.path);
  252. const owner = doc.ownerDocument ? doc.ownerDocument() : doc;
  253. const pop = owner.populated(path, true);
  254. const ret = new pop.options.model(value);
  255. ret.$__.wasPopulated = true;
  256. return ret;
  257. }
  258. const val = value && typeof value._id !== 'undefined' ?
  259. value._id : // documents
  260. value;
  261. try {
  262. return this.constructor.cast()(val);
  263. } catch (err) {
  264. throw new CastError('number', val, this.path);
  265. }
  266. };
  267. /*!
  268. * ignore
  269. */
  270. function handleSingle(val) {
  271. return this.cast(val);
  272. }
  273. function handleArray(val) {
  274. const _this = this;
  275. if (!Array.isArray(val)) {
  276. return [this.cast(val)];
  277. }
  278. return val.map(function(m) {
  279. return _this.cast(m);
  280. });
  281. }
  282. SchemaNumber.prototype.$conditionalHandlers =
  283. utils.options(SchemaType.prototype.$conditionalHandlers, {
  284. $bitsAllClear: handleBitwiseOperator,
  285. $bitsAnyClear: handleBitwiseOperator,
  286. $bitsAllSet: handleBitwiseOperator,
  287. $bitsAnySet: handleBitwiseOperator,
  288. $gt: handleSingle,
  289. $gte: handleSingle,
  290. $lt: handleSingle,
  291. $lte: handleSingle,
  292. $mod: handleArray
  293. });
  294. /**
  295. * Casts contents for queries.
  296. *
  297. * @param {String} $conditional
  298. * @param {any} [value]
  299. * @api private
  300. */
  301. SchemaNumber.prototype.castForQuery = function($conditional, val) {
  302. let handler;
  303. if (arguments.length === 2) {
  304. handler = this.$conditionalHandlers[$conditional];
  305. if (!handler) {
  306. throw new CastError('Can\'t use ' + $conditional + ' with Number.');
  307. }
  308. return handler.call(this, val);
  309. }
  310. val = this._castForQuery($conditional);
  311. return val;
  312. };
  313. /*!
  314. * Module exports.
  315. */
  316. module.exports = SchemaNumber;