const UserSchema = new mongoose.Schema({
// String with validation
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email']
},
// String with enum
role: {
type: String,
enum: {
values: ['user', 'admin', 'moderator'],
message: '{VALUE} is not a valid role'
},
default: 'user'
},
// Number with min/max
age: {
type: Number,
min: [18, 'Must be at least 18'],
max: [120, 'Invalid age']
},
// Array of strings
tags: [String],
// Nested object
address: {
street: String,
city: String,
zipCode: {
type: String,
validate: {
validator: (v) => /^\d{5}(-\d{4})?$/.test(v),
message: 'Invalid zip code'
}
}
},
// Reference to another model
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true, // Adds createdAt and updatedAt
toJSON: { virtuals: true },
toObject: { virtuals: true }
});