Schema (Mongoose)
A Mongoose schema defines the shape of documents in a MongoDB collection: each field's name, type, default, and validation rules. It is compiled into a model that enforces that structure on the otherwise schemaless database.
Node.js
The schema is where you impose structure on MongoDB's flexible documents. You declare each field with a type (String, Number, Boolean, Date, ObjectId for references, arrays, nested objects) and options like required, default, unique, min/max, and enum, so invalid data is rejected before it is saved.
Beyond field definitions, a schema can hold instance methods (custom functions on each document), static methods (on the model), virtuals (computed fields not stored in the database, like fullName), indexes for query performance, and middleware hooks such as pre('save') to run code before persisting (commonly to hash a password).
You turn a schema into a usable model with mongoose.model('Name', schema), and Mongoose maps it to a lowercased, pluralized collection (User -> users). Designing good schemas — choosing embedding versus referencing related data — is the main modeling decision in a Mongoose app.
Syntax
const schema = new mongoose.Schema({ name: String });Examples
JavaScript
const mongoose = require("mongoose");
const postSchema = new mongoose.Schema({
title: { type: String, required: true },
tags: [String],
author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
createdAt: { type: Date, default: Date.now },
});
module.exports = mongoose.model("Post", postSchema);