Mongoose
Schema, Model and Documents
The three objects you will touch in every Mongoose file.
Three names. Schema — the shape and types. Model — the class bound to a collection (User → users by default). Document — one hydrated record, with .save(). Mixing them up is how people call new Schema().find().
import mongoose, { Schema } from "mongoose";
const userSchema = new Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
city: String,
age: Number,
skills: [String],
},
{ timestamps: true }
);
export const User = mongoose.model("User", userSchema);const orderSchema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
amount: Number,
status: { type: String, enum: ["pending", "shipped", "delivered", "cancelled"] },
items: [{ name: String, quantity: Number, unitPrice: Number }],
});
export const Order = mongoose.model("Order", orderSchema);unique: true on the schema creates an index; it is not the same as required validation. strict (default) strips fields not in the schema on save — a driver insert can still store them. timestamps adds createdAt / updatedAt. Override the collection with { collection: "app_users" } when you do not want users.
Interview question
What is the difference between a Mongoose schema, model and document?
The schema declares fields and types. The model is compiled from that schema and talks to a collection — User maps to users. A document is one hydrated instance with save(). unique on the schema is an index, not a validator like required.