SchemaType.prototype.required()

Parameters
  • required «Boolean|Function|Object» enable/disable the validator, or function that returns required boolean, or options object

  • [options.isRequired] «Boolean|Function» enable/disable the validator, or function that returns required boolean

  • [options.ErrorConstructor] «Function» custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.

  • [message] «String» optional custom error message

Returns:
  • «SchemaType» this

Adds a required validator to this SchemaType. The validator gets added to the front of this SchemaType’s validators array using unshift().

Example:

  1. const s = new Schema({ born: { type: Date, required: true })
  2. // or with custom error message
  3. const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
  4. // or with a function
  5. const s = new Schema({
  6. userId: ObjectId,
  7. username: {
  8. type: String,
  9. required: function() { return this.userId != null; }
  10. }
  11. })
  12. // or with a function and a custom message
  13. const s = new Schema({
  14. userId: ObjectId,
  15. username: {
  16. type: String,
  17. required: [
  18. function() { return this.userId != null; },
  19. 'username is required if id is specified'
  20. ]
  21. }
  22. })
  23. // or through the path API
  24. s.path('name').required(true);
  25. // with custom error messaging
  26. s.path('name').required(true, 'grrr :( ');
  27. // or make a path conditionally required based on a function
  28. const isOver18 = function() { return this.age >= 18; };
  29. s.path('voterRegistrationId').required(isOver18);

The required validator uses the SchemaType’s checkRequired function to determine whether a given value satisfies the required validator. By default, a value satisfies the required validator if val != null (that is, if the value is not null nor undefined). However, most built-in mongoose schema types override the default checkRequired function: