string.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*!
  2. * Module dependencies.
  3. */
  4. var SchemaType = require('../schematype')
  5. , CastError = SchemaType.CastError
  6. , errorMessages = require('../error').messages
  7. , utils = require('../utils')
  8. , Document
  9. /**
  10. * String SchemaType constructor.
  11. *
  12. * @param {String} key
  13. * @param {Object} options
  14. * @inherits SchemaType
  15. * @api private
  16. */
  17. function SchemaString (key, options) {
  18. this.enumValues = [];
  19. this.regExp = null;
  20. SchemaType.call(this, key, options, 'String');
  21. };
  22. /**
  23. * This schema type's name, to defend against minifiers that mangle
  24. * function names.
  25. *
  26. * @api private
  27. */
  28. SchemaString.schemaName = 'String';
  29. /*!
  30. * Inherits from SchemaType.
  31. */
  32. SchemaString.prototype = Object.create( SchemaType.prototype );
  33. SchemaString.prototype.constructor = SchemaString;
  34. /**
  35. * Adds an enum validator
  36. *
  37. * ####Example:
  38. *
  39. * var states = 'opening open closing closed'.split(' ')
  40. * var s = new Schema({ state: { type: String, enum: states }})
  41. * var M = db.model('M', s)
  42. * var m = new M({ state: 'invalid' })
  43. * m.save(function (err) {
  44. * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
  45. * m.state = 'open'
  46. * m.save(callback) // success
  47. * })
  48. *
  49. * // or with custom error messages
  50. * var enu = {
  51. * values: 'opening open closing closed'.split(' '),
  52. * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
  53. * }
  54. * var s = new Schema({ state: { type: String, enum: enu })
  55. * var M = db.model('M', s)
  56. * var m = new M({ state: 'invalid' })
  57. * m.save(function (err) {
  58. * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid`
  59. * m.state = 'open'
  60. * m.save(callback) // success
  61. * })
  62. *
  63. * @param {String|Object} [args...] enumeration values
  64. * @return {SchemaType} this
  65. * @see Customized Error Messages #error_messages_MongooseError-messages
  66. * @api public
  67. */
  68. SchemaString.prototype.enum = function () {
  69. if (this.enumValidator) {
  70. this.validators = this.validators.filter(function(v) {
  71. return v.validator != this.enumValidator;
  72. }, this);
  73. this.enumValidator = false;
  74. }
  75. if (undefined === arguments[0] || false === arguments[0]) {
  76. return this;
  77. }
  78. var values;
  79. var errorMessage;
  80. if (utils.isObject(arguments[0])) {
  81. values = arguments[0].values;
  82. errorMessage = arguments[0].message;
  83. } else {
  84. values = arguments;
  85. errorMessage = errorMessages.String.enum;
  86. }
  87. for (var i = 0; i < values.length; i++) {
  88. if (undefined !== values[i]) {
  89. this.enumValues.push(this.cast(values[i]));
  90. }
  91. }
  92. var vals = this.enumValues;
  93. this.enumValidator = function (v) {
  94. return undefined === v || ~vals.indexOf(v);
  95. };
  96. this.validators.push({
  97. validator: this.enumValidator,
  98. message: errorMessage,
  99. type: 'enum'
  100. });
  101. return this;
  102. };
  103. /**
  104. * Adds a lowercase setter.
  105. *
  106. * ####Example:
  107. *
  108. * var s = new Schema({ email: { type: String, lowercase: true }})
  109. * var M = db.model('M', s);
  110. * var m = new M({ email: 'SomeEmail@example.COM' });
  111. * console.log(m.email) // someemail@example.com
  112. *
  113. * @api public
  114. * @return {SchemaType} this
  115. */
  116. SchemaString.prototype.lowercase = function () {
  117. return this.set(function (v, self) {
  118. if ('string' != typeof v) v = self.cast(v)
  119. if (v) return v.toLowerCase();
  120. return v;
  121. });
  122. };
  123. /**
  124. * Adds an uppercase setter.
  125. *
  126. * ####Example:
  127. *
  128. * var s = new Schema({ caps: { type: String, uppercase: true }})
  129. * var M = db.model('M', s);
  130. * var m = new M({ caps: 'an example' });
  131. * console.log(m.caps) // AN EXAMPLE
  132. *
  133. * @api public
  134. * @return {SchemaType} this
  135. */
  136. SchemaString.prototype.uppercase = function () {
  137. return this.set(function (v, self) {
  138. if ('string' != typeof v) v = self.cast(v)
  139. if (v) return v.toUpperCase();
  140. return v;
  141. });
  142. };
  143. /**
  144. * Adds a trim setter.
  145. *
  146. * The string value will be trimmed when set.
  147. *
  148. * ####Example:
  149. *
  150. * var s = new Schema({ name: { type: String, trim: true }})
  151. * var M = db.model('M', s)
  152. * var string = ' some name '
  153. * console.log(string.length) // 11
  154. * var m = new M({ name: string })
  155. * console.log(m.name.length) // 9
  156. *
  157. * @api public
  158. * @return {SchemaType} this
  159. */
  160. SchemaString.prototype.trim = function () {
  161. return this.set(function (v, self) {
  162. if ('string' != typeof v) v = self.cast(v)
  163. if (v) return v.trim();
  164. return v;
  165. });
  166. };
  167. /**
  168. * Sets a minimum length validator.
  169. *
  170. * ####Example:
  171. *
  172. * var schema = new Schema({ postalCode: { type: String, minlength: 5 })
  173. * var Address = db.model('Address', schema)
  174. * var address = new Address({ postalCode: '9512' })
  175. * address.save(function (err) {
  176. * console.error(err) // validator error
  177. * address.postalCode = '95125';
  178. * address.save() // success
  179. * })
  180. *
  181. * // custom error messages
  182. * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length
  183. * var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'];
  184. * var schema = new Schema({ postalCode: { type: String, minlength: minlength })
  185. * var Address = mongoose.model('Address', schema);
  186. * var address = new Address({ postalCode: '9512' });
  187. * address.validate(function (err) {
  188. * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
  189. * })
  190. *
  191. * @param {Number} value minimum string length
  192. * @param {String} [message] optional custom error message
  193. * @return {SchemaType} this
  194. * @see Customized Error Messages #error_messages_MongooseError-messages
  195. * @api public
  196. */
  197. SchemaString.prototype.minlength = function (value, message) {
  198. if (this.minlengthValidator) {
  199. this.validators = this.validators.filter(function (v) {
  200. return v.validator != this.minlengthValidator;
  201. }, this);
  202. }
  203. if (null != value) {
  204. var msg = message || errorMessages.String.minlength;
  205. msg = msg.replace(/{MINLENGTH}/, value);
  206. this.validators.push({
  207. validator: this.minlengthValidator = function (v) {
  208. return v === null || v.length >= value;
  209. },
  210. message: msg,
  211. type: 'minlength'
  212. });
  213. }
  214. return this;
  215. };
  216. /**
  217. * Sets a maximum length validator.
  218. *
  219. * ####Example:
  220. *
  221. * var schema = new Schema({ postalCode: { type: String, maxlength: 9 })
  222. * var Address = db.model('Address', schema)
  223. * var address = new Address({ postalCode: '9512512345' })
  224. * address.save(function (err) {
  225. * console.error(err) // validator error
  226. * address.postalCode = '95125';
  227. * address.save() // success
  228. * })
  229. *
  230. * // custom error messages
  231. * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length
  232. * var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
  233. * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
  234. * var Address = mongoose.model('Address', schema);
  235. * var address = new Address({ postalCode: '9512512345' });
  236. * address.validate(function (err) {
  237. * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9).
  238. * })
  239. *
  240. * @param {Number} value maximum string length
  241. * @param {String} [message] optional custom error message
  242. * @return {SchemaType} this
  243. * @see Customized Error Messages #error_messages_MongooseError-messages
  244. * @api public
  245. */
  246. SchemaString.prototype.maxlength = function (value, message) {
  247. if (this.maxlengthValidator) {
  248. this.validators = this.validators.filter(function(v){
  249. return v.validator != this.maxlengthValidator;
  250. }, this);
  251. }
  252. if (null != value) {
  253. var msg = message || errorMessages.String.maxlength;
  254. msg = msg.replace(/{MAXLENGTH}/, value);
  255. this.validators.push({
  256. validator: this.maxlengthValidator = function(v) {
  257. return v === null || v.length <= value;
  258. },
  259. message: msg,
  260. type: 'maxlength'
  261. });
  262. }
  263. return this;
  264. };
  265. /**
  266. * Sets a regexp validator.
  267. *
  268. * Any value that does not pass `regExp`.test(val) will fail validation.
  269. *
  270. * ####Example:
  271. *
  272. * var s = new Schema({ name: { type: String, match: /^a/ }})
  273. * var M = db.model('M', s)
  274. * var m = new M({ name: 'I am invalid' })
  275. * m.validate(function (err) {
  276. * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
  277. * m.name = 'apples'
  278. * m.validate(function (err) {
  279. * assert.ok(err) // success
  280. * })
  281. * })
  282. *
  283. * // using a custom error message
  284. * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
  285. * var s = new Schema({ file: { type: String, match: match }})
  286. * var M = db.model('M', s);
  287. * var m = new M({ file: 'invalid' });
  288. * m.validate(function (err) {
  289. * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)"
  290. * })
  291. *
  292. * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also.
  293. *
  294. * var s = new Schema({ name: { type: String, match: /^a/, required: true }})
  295. *
  296. * @param {RegExp} regExp regular expression to test against
  297. * @param {String} [message] optional custom error message
  298. * @return {SchemaType} this
  299. * @see Customized Error Messages #error_messages_MongooseError-messages
  300. * @api public
  301. */
  302. SchemaString.prototype.match = function match (regExp, message) {
  303. // yes, we allow multiple match validators
  304. var msg = message || errorMessages.String.match;
  305. var matchValidator = function(v) {
  306. if (!regExp) {
  307. return false;
  308. }
  309. var ret = ((null != v && '' !== v)
  310. ? regExp.test(v)
  311. : true);
  312. return ret;
  313. };
  314. this.validators.push({ validator: matchValidator, message: msg, type: 'regexp' });
  315. return this;
  316. };
  317. /**
  318. * Check required
  319. *
  320. * @param {String|null|undefined} value
  321. * @api private
  322. */
  323. SchemaString.prototype.checkRequired = function checkRequired (value, doc) {
  324. if (SchemaType._isRef(this, value, doc, true)) {
  325. return null != value;
  326. } else {
  327. return (value instanceof String || typeof value == 'string') && value.length;
  328. }
  329. };
  330. /**
  331. * Casts to String
  332. *
  333. * @api private
  334. */
  335. SchemaString.prototype.cast = function (value, doc, init) {
  336. if (SchemaType._isRef(this, value, doc, init)) {
  337. // wait! we may need to cast this to a document
  338. if (null == value) {
  339. return value;
  340. }
  341. // lazy load
  342. Document || (Document = require('./../document'));
  343. if (value instanceof Document) {
  344. value.$__.wasPopulated = true;
  345. return value;
  346. }
  347. // setting a populated path
  348. if ('string' == typeof value) {
  349. return value;
  350. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
  351. throw new CastError('string', value, this.path);
  352. }
  353. // Handle the case where user directly sets a populated
  354. // path to a plain object; cast to the Model used in
  355. // the population query.
  356. var path = doc.$__fullPath(this.path);
  357. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
  358. var pop = owner.populated(path, true);
  359. var ret = new pop.options.model(value);
  360. ret.$__.wasPopulated = true;
  361. return ret;
  362. }
  363. // If null or undefined
  364. if (value == null) {
  365. return value;
  366. }
  367. if ('undefined' !== typeof value) {
  368. // handle documents being passed
  369. if (value._id && 'string' == typeof value._id) {
  370. return value._id;
  371. }
  372. // Re: gh-647 and gh-3030, we're ok with casting using `toString()`
  373. // **unless** its the default Object.toString, because "[object Object]"
  374. // doesn't really qualify as useful data
  375. if (value.toString && value.toString !== Object.prototype.toString) {
  376. return value.toString();
  377. }
  378. }
  379. throw new CastError('string', value, this.path);
  380. };
  381. /*!
  382. * ignore
  383. */
  384. function handleSingle (val) {
  385. return this.castForQuery(val);
  386. }
  387. function handleArray (val) {
  388. var self = this;
  389. return val.map(function (m) {
  390. return self.castForQuery(m);
  391. });
  392. }
  393. SchemaString.prototype.$conditionalHandlers =
  394. utils.options(SchemaType.prototype.$conditionalHandlers, {
  395. '$all': handleArray,
  396. '$gt' : handleSingle,
  397. '$gte': handleSingle,
  398. '$in' : handleArray,
  399. '$lt' : handleSingle,
  400. '$lte': handleSingle,
  401. '$ne' : handleSingle,
  402. '$nin': handleArray,
  403. '$options': handleSingle,
  404. '$regex': handleSingle
  405. });
  406. /**
  407. * Casts contents for queries.
  408. *
  409. * @param {String} $conditional
  410. * @param {any} [val]
  411. * @api private
  412. */
  413. SchemaString.prototype.castForQuery = function ($conditional, val) {
  414. var handler;
  415. if (arguments.length === 2) {
  416. handler = this.$conditionalHandlers[$conditional];
  417. if (!handler)
  418. throw new Error("Can't use " + $conditional + " with String.");
  419. return handler.call(this, val);
  420. } else {
  421. val = $conditional;
  422. if (val instanceof RegExp) return val;
  423. return this.cast(val);
  424. }
  425. };
  426. /*!
  427. * Module exports.
  428. */
  429. module.exports = SchemaString;