intermediate

Schemas

Define document shape, defaults, indexes, virtuals, and nested structures while respecting MongoDB aggregate boundaries.

Mongoose schemas define document shape: fields, types, defaults, indexes, virtuals, timestamps, and nested paths. They are application-level modeling—not a substitute for MongoDB aggregate design.

					const orderSchema = new Schema({
  customerId: { type: String, required: true, index: true },
  status: { type: String, enum: ['pending', 'paid'], default: 'pending' },
  items: [{ sku: String, qty: Number }],
}, { timestamps: true });
				

On interviews: explain embedding versus referencing, schema evolution, indexes, validation boundaries, and how schema choices shape query patterns.

Common pitfalls: copying relational table-per-entity habits into documents; huge unbounded arrays; missing indexes on hot filters; treating schema as full database enforcement.

The trade-off is flexible document modeling versus predictable query performance and growth control.

Checklist:

  • Model aggregate boundaries in the document.
  • Define indexes for real access paths.
  • Plan document growth and schema changes.
  • Align validation with API and DB constraints.