Mongoose Schema is a core concept in Mongoose used to define the structure, data types, validation rules, and default values of MongoDB documents. Schema itself is not a collection in the database, but a blueprint used to create Models.
Basic Schema Definition
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ name: { type: String, required: true, trim: true }, email: { type: String, required: true, unique: true, lowercase: true, trim: true }, age: { type: Number, min: 0, max: 120 }, createdAt: { type: Date, default: Date.now } });
Main Schema Properties
- Field Types: String, Number, Date, Buffer, Boolean, Mixed, ObjectId, Array
- Validators: required, min, max, enum, match, validate
- Modifiers: lowercase, uppercase, trim, default
- Indexes: unique, sparse, index
- Virtual Fields: Computed fields not stored in database
- Instance Methods: Methods added to document instances
- Static Methods: Methods added to model classes
- Middleware: pre and post hooks
Relationship Between Schema and Model
- Schema is the definition, Model is the constructor
- Create Model via
mongoose.model('User', userSchema) - Model instances are Documents, representing actual documents in the database
- One Schema can create multiple Models (not recommended)
Schema Advantages
- Data Consistency: Enforce consistent document structure
- Data Validation: Validate data at application layer
- Type Safety: Provide type checking and conversion
- Middleware Support: Execute logic before/after operations
- Extensibility: Add methods and virtual fields