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:
const s = new Schema({ born: { type: Date, required: true })
// or with custom error message
const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
// or with a function
const s = new Schema({
userId: ObjectId,
username: {
type: String,
required: function() { return this.userId != null; }
}
})
// or with a function and a custom message
const s = new Schema({
userId: ObjectId,
username: {
type: String,
required: [
function() { return this.userId != null; },
'username is required if id is specified'
]
}
})
// or through the path API
s.path('name').required(true);
// with custom error messaging
s.path('name').required(true, 'grrr :( ');
// or make a path conditionally required based on a function
const isOver18 = function() { return this.age >= 18; };
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: