Schema definition
A Mongoose schema declares each field's type and rules such as required, default, enum and min.
In this page:
Syntax
const schema = new mongoose.Schema({
field: { type: Type, required: true, default: value },
other: String
});
Schema definition
Fields accept a type or an options object with required, default, unique, enum, min, max, match and custom validators.
The timestamps option adds createdAt and updatedAt. Sub-schemas embed structured data and arrays hold lists.
The unique option builds an index rather than validating.
Note:
unique creates an index; it is not a validator, so handle duplicate key errors.
Example: Schema definition
const productSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true },
price: { type: Number, min: 0, default: 0 },
category: { type: String, enum: ["office", "home", "toys"] },
tags: [String],
sku: { type: String, unique: true },
}, { timestamps: true });
const Product = mongoose.model("Product", productSchema);
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Assuming unique validates like required
- Forgetting the array of type syntax
- Skipping timestamps
Chapter Summary
- Types with options
- required, default, enum, min, max
- timestamps adds dates
- unique builds an index
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: