← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 3 of 7

Schema definition

A Mongoose schema declares each field's type and rules such as required, default, enum and min.

In this page:

  1. Schema definition
Syntax
javascript
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

javascript
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
  1. Assuming unique validates like required
  2. Forgetting the array of type syntax
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.