5 min read
•Question 14 of 27easyWhat are Mongoose schema types and validators?
Understanding schema definitions.
What You'll Learn
- Schema types
- Built-in validators
- Custom validators
Schema Types
code.jsJavaScript
const schema = new mongoose.Schema({
// String
name: String,
// Number
age: Number,
// Boolean
isActive: Boolean,
// Date
createdAt: Date,
// ObjectId reference
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
// Array of strings
tags: [String],
// Array of objects
comments: [{ text: String, date: Date }],
// Nested object
address: {
street: String,
city: String,
zip: String
},
// Mixed (any type)
metadata: mongoose.Schema.Types.Mixed
});Built-in Validators
code.jsJavaScript
const userSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, 'Invalid email']
},
age: {
type: Number,
min: [0, 'Age cannot be negative'],
max: [120, 'Age too high']
},
role: {
type: String,
enum: ['user', 'admin', 'moderator'],
default: 'user'
},
username: {
type: String,
minlength: 3,
maxlength: 30
}
});Custom Validators
code.jsJavaScript
const schema = new mongoose.Schema({
phone: {
type: String,
validate: {
validator: function(v) {
return /\d{10}/.test(v);
},
message: 'Invalid phone number'
}
}
});