Q5: What is the difference between a Mongoose Schema and a Mongoose Model?
A Schema defines the structure, default values, validators, and middleware hooks for documents within a collection. A Model is a compiled constructor built from a Schema that provides the concrete interface to perform database CRUD operations (User.find(), User.create()).
Schema Definition vs Model Creation
const mongoose = require('mongoose');
// 1. Define Schema (Blueprint)
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, unique: true }
});
// 2. Compile Model (Database Interface)
const User = mongoose.model('User', userSchema);💡 The Schema defines attributes and rules; the Model compiles the schema into an executable database interface.
Key Takeaways
- Schema = Blueprint & Rules.
- Model = Compiled class providing CRUD access methods.
Knowledge Check
Which Mongoose call creates the database query interface from a defined schema?