Careeroza
Models
Compilation
1. MongoDB Models in Code (Mongoose)
If you are using Node.js, especially with Mongoose, a model is something different:
A model is a wrapper around a collection
It is used to interact with MongoDB in code
Example idea:
You define a schema:
- name
- age
Then create a model:
- User model → works with users collection
What Model Does
- Insert data
- Fetch data
- Update data
- Delete data
Instead of writing raw queries, you use model methods
🔹 Example: User Model
Step 1: Define Schema
Structure of data
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
isActive: Boolean
})Step 2: Create Model
Connect schema to collection
const User = mongoose.model("User", userSchema)
"User" → model name
MongoDB creates collection → users
🔹 Step 3: Use the Model
Insert Data
User.create({
name: "Rahul",
age: 25,
email: "[email protected]",
isActive: true
})Read Data
User.find({ age: 25 })Update Data
User.updateOne(
{ name: "Rahul" },
{ age: 26 }
)Delete Data
User.deleteOne({ name: "Rahul" })
Simple Understanding
- Schema → structure
- Model → tool to interact with DB
- Model methods → CRUD operations