/node_modules/mongoose/docs/validation.md

https://github.com/anatolyg/node-sane · Markdown · 90 lines · 61 code · 29 blank · 0 comment · 0 complexity · 566c8c6a62cf832807fa7f9ea664cb89 MD5 · raw file

  1. Validation in models
  2. ====================
  3. Before we get into the specifics of validation syntax, please keep the
  4. following rules in mind:
  5. - Validation is defined in the `Schema`
  6. - Validation occurs when a document attempts to be saved, after defaults have
  7. been applied.
  8. - Mongoose doesn't care about complex error message construction. Errors have
  9. type identifiers. For example, `"min"` is the identifier for the error
  10. triggered when a number doesn't meet the minimum value. The path and value
  11. that triggered the error can be accessed in the `ValidationError` object.
  12. - Validation is an internal piece of middleware
  13. - Validation is asynchronously recursive: when you call `Model#save`, embedded
  14. documents validation is executed. If an error happens, your `Model#save`
  15. callback receives it.
  16. ## Simple validation
  17. Simple validation is declared by passing a function to `validate` and an error
  18. type to your `SchemaType` (please read the chapter on model definition to learn
  19. more about schemas).
  20. function validator (v) {
  21. return v.length > 5;
  22. };
  23. new Schema({
  24. name: { type: String, validate: [validator, 'my error type'] }
  25. })
  26. If you find this syntax too clumsy, you can also define the type
  27. var schema = new Schema({
  28. name: String
  29. })
  30. and then your validator
  31. schema.path('name').validate(function (v) {
  32. return v.length > 5;
  33. }, 'my error type');
  34. ## Regular expressions
  35. If you want to test a certain value against a regular expression:
  36. var schema = new Schema({
  37. name: { type: String, validate: /[a-z]/ }
  38. });
  39. ## Asynchronous validation
  40. If you define a validator function with two parameters, like:
  41. schema.path('name').validate(function (v, fn) {
  42. // my logic
  43. }, 'my error type');
  44. Then the function `fn` has to be called with `true` or `false`, depending on
  45. whether the validator passed. This allows for calling other models and querying
  46. data asynchronously from your validator.
  47. ## Built in validators
  48. - For Strings:
  49. - `enum`: takes a list of allowed values. Example:
  50. var Post = new Schema({
  51. type: { type: String, enum: ['page', 'post', 'link'] }
  52. })
  53. - For Numbers:
  54. - `min`: minimum value
  55. var Person = new Schema({
  56. age: { type: Number, min: 5 }
  57. })
  58. - `max`: maxmimum value
  59. var Person = new Schema({
  60. age: { type: Number, max: 100 }
  61. })