Mongodb Guide

Difference between Schema and Model in Mongoose

1. Definition

In Mongoose, a Schema defines the structure of data, while a Model is used to interact with the database using that schema.

2. Simple Understanding

👉 Schema = Blueprint (structure of data)
👉 Model = Tool (used to perform operations)

3. Key Differences

FeatureSchemaModel
DefinitionDefines structureInteracts with DB
PurposeData designCRUD operations
UsageCreate modelUse in app logic
Direct DB Access❌ No✅ Yes

4. When to Use

  • Use Schema when defining structure
  • Use Model when performing operations

5. How They Work Together

  • Step 1: Create Schema
  • Step 2: Create Model using Schema
  • Step 3: Use Model for CRUD operations

6. Basic Syntax

const mongoose = require("mongoose");

// Schema
const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

// Model
const User = mongoose.model("User", userSchema);

7. Real Example

// Create user
const user = new User({
  name: "Manaswini",
  age: 23
});

user.save();

// Fetch users
User.find().then(data => console.log(data));

8. Explanation

  • Schema defines data fields
  • Model uses schema to interact with DB
  • Model performs CRUD operations

9. Advantages

  • Clear data structure
  • Separation of concerns
  • Easy data management

Interview Points

  • Schema = structure (blueprint)
  • Model = database interaction
  • Model is created from schema
  • Model performs CRUD operations