Why MongoDB?
MongoDB is a NoSQL database that stores data as JSON-like documents. Perfect for JavaScript developers!
| SQL (MySQL) | MongoDB |
|---|---|
| Tables | Collections |
| Rows | Documents |
| Columns | Fields |
| SQL queries | JavaScript methods |
MongoDB Document Example
// A document in the "users" collection
{
"_id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"age": 28,
"hobbies": ["coding", "gaming"],
"address": {
"city": "Beirut",
"country": "Lebanon"
},
"createdAt": "2024-01-15T10:30:00Z"
}
Setting Up MongoDB
Option 1: MongoDB Atlas (Cloud - Recommended)
mongodb+srv://user:pass@cluster.mongodb.net/mydb)
Option 2: Local MongoDB
# Install MongoDB locally (or use Docker)
# Connection string: mongodb://localhost:27017/mydb
Mongoose - MongoDB ODM
Mongoose is an Object Data Modeling (ODM) library that makes working with MongoDB easier.
Install Mongoose
Important: Mongoose must be installed in every project that uses MongoDB. It gets added to your package.json file as a dependency.
# In your project directory, run:
npm install mongoose
- Adds mongoose to
package.json: This file lists all your project's dependencies (packages you need) - Creates
node_modulesfolder: This is where all installed packages are stored - Should be in every MongoDB project: If you're using MongoDB with Node.js, you need mongoose installed
- Once installed: You can use
require('mongoose')in your code
npm install to install all dependencies (including mongoose) listed in package.json.
Connect to MongoDB
// db.js - Database connection
const mongoose = require('mongoose');
// Connection string (use environment variable in production!)
const MONGODB_URI = 'mongodb://localhost:27017/myapp';
// Or for Atlas: 'mongodb+srv://user:pass@cluster.mongodb.net/myapp'
async function connectDB() {
try {
await mongoose.connect(MONGODB_URI);
console.log('✅ Connected to MongoDB');
} catch (error) {
console.error('❌ MongoDB connection error:', error.message);
process.exit(1);
}
}
module.exports = connectDB;
7.1 Creating a Model (Schema)
A Schema defines the structure of documents in a collection:
// models/User.js
const mongoose = require('mongoose');
// Define the schema
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required'],
trim: true
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true
},
age: {
type: Number,
min: [0, 'Age cannot be negative'],
max: [150, 'Age too high']
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user'
},
isActive: {
type: Boolean,
default: true
}
}, {
timestamps: true // Adds createdAt and updatedAt
});
// Create and export the model
module.exports = mongoose.model('User', userSchema);
Common Schema Types
| Type | Description | Example |
|---|---|---|
| String | Text | "John" |
| Number | Integers, floats | 25, 99.99 |
| Boolean | true/false | true |
| Date | Dates | new Date() |
| Array | Lists | [String] |
| ObjectId | References | mongoose.Schema.Types.ObjectId |
7.2 Methods Available After Creating a Model ⭐
Once you create a model with mongoose.model('User', userSchema), you get access to many methods for database operations.
📌 CREATE Methods
1. Model.create(data) - Create one or multiple documents
// Create a single document
const user = await User.create({
name: 'John Doe',
email: 'john@example.com',
age: 28
});
// Returns the created document
// Create multiple documents at once
const users = await User.create([
{ name: 'Alice', email: 'alice@example.com' },
{ name: 'Bob', email: 'bob@example.com' }
]);
// Returns an array of created documents
2. new Model(data) + .save() - Create with more control
// Create instance, modify it, then save
const user = new User({
name: 'John Doe',
email: 'john@example.com'
});
// You can modify before saving
user.age = 28;
user.role = 'admin';
// Save to database
const savedUser = await user.save();
// Returns the saved document
•
create() - Simple, direct creation•
new Model() + save() - When you need to modify or validate before saving
📖 READ Methods
1. Model.find(filter) - Find multiple documents
How find() works: The find() method searches for documents in the database collection and returns an array of all matching documents. If no filter is provided, it returns all documents.
// Find all users (no filter = returns everything)
const allUsers = await User.find();
// Returns: [{...}, {...}, {...}] - array of all users
// Find with conditions (filter object)
const adults = await User.find({ age: { $gte: 18 } });
// Returns: [{...}, {...}] - array of users with age >= 18
// $gte means "greater than or equal to"
// Find with multiple conditions (AND logic)
const activeAdmins = await User.find({
role: 'admin', // Must be admin
isActive: true // AND must be active
});
// Returns: [{...}] - array of users who are both admin AND active
// Find returns empty array if nothing matches
const noResults = await User.find({ age: 999 });
// Returns: [] - empty array (no users with age 999)
$gte- Greater than or equal$lte- Less than or equal$gt- Greater than$lt- Less than$ne- Not equal$in- In array$regex- Regular expression
2. Model.findOne(filter) - Find one document
// Find one user by email
const user = await User.findOne({ email: 'john@example.com' });
// Returns the first matching document or null
// Find one with conditions
const admin = await User.findOne({ role: 'admin', isActive: true });
3. Model.findById(id) - Find by ID
// Find user by MongoDB _id
const user = await User.findById('507f1f77bcf86cd799439011');
// Returns the document or null if not found
// Shorthand for: User.findOne({ _id: id })
4. Query Chain Methods (Chaining After find())
What is chaining? After calling find(), you can chain additional methods to refine, sort, and limit your query results. These methods modify the query before it executes.
.select(), .sort(), .limit(), and .skip() can be chained together because find() returns a Query object, not the results immediately. The query only executes when you use await.
// 1. Select specific fields only (return only name and email)
const users = await User.find()
.select('name email');
// Result: [{ name: "John", email: "john@example.com" }, ...]
// Note: Only name and email fields are returned, other fields are excluded
// 2. Exclude fields (return everything EXCEPT password and __v)
const users = await User.find()
.select('-password -__v');
// Use minus (-) prefix to exclude fields
// Result: All fields except password and __v
// 3. Sort results (order the results)
const users = await User.find()
.sort({ createdAt: -1 });
// -1 = descending (newest first: 2024, 2023, 2022...)
// 1 = ascending (oldest first: 2022, 2023, 2024...)
// Result: Users sorted by creation date, newest first
// 4. Limit number of results (only get first N documents)
const users = await User.find()
.limit(10);
// Result: Only the first 10 users (or less if fewer exist)
// 5. Skip documents (for pagination - skip first N documents)
const users = await User.find()
.skip(10) // Skip the first 10 users
.limit(10); // Return the next 10 users
// Useful for pagination: page 2 of results (skip 10, limit 10)
// Page 1: skip(0).limit(10) → users 1-10
// Page 2: skip(10).limit(10) → users 11-20
// Page 3: skip(20).limit(10) → users 21-30
// 6. Combine multiple chain methods (most powerful!)
const recentActiveUsers = await User.find({ isActive: true }) // Filter: only active users
.select('name email') // Only return name and email
.sort({ createdAt: -1 }) // Sort by newest first
.limit(10); // Only return 10 results
// Result: 10 newest active users with only name and email fields
// Query executes only when await is used at the end!
- Start with
find(filter)to filter documents - Use
.select()to choose fields - Use
.sort()to order results - Use
.skip()and.limit()for pagination - Use
awaitto execute the query
5. Model.countDocuments(filter) - Count documents
What does it do? Counts how many documents match the filter criteria. Returns a number (not the actual documents). Useful for getting statistics or checking how many records exist.
// Count all users in the collection
const total = await User.countDocuments();
// Returns: 150 (a number, not an array of documents!)
// This is more efficient than User.find().length because it doesn't load all documents
// Count with filter conditions (same syntax as find())
const activeCount = await User.countDocuments({ isActive: true });
// Returns: 120 (number of users where isActive is true)
// Count with multiple conditions
const adminCount = await User.countDocuments({
role: 'admin',
isActive: true
});
// Returns: 5 (number of active admin users)
// Common use cases:
// 1. Check if collection is empty
const count = await User.countDocuments();
if (count === 0) {
console.log('No users found!');
}
// 2. Display statistics
const totalUsers = await User.countDocuments();
const activeUsers = await User.countDocuments({ isActive: true });
console.log(`Total: ${totalUsers}, Active: ${activeUsers}`);
// Output: Total: 150, Active: 120
// 3. For pagination (calculate total pages)
const total = await User.countDocuments({ isActive: true });
const itemsPerPage = 10;
const totalPages = Math.ceil(total / itemsPerPage);
// If total = 150, itemsPerPage = 10, then totalPages = 15
countDocuments()returns a number, not documents or an array- Much more efficient than
User.find().lengthbecause it doesn't load all documents into memory - Uses the same filter syntax as
find() - If no documents match, returns
0
6. Model.exists(filter) - Check if document exists
// Check if user exists
const exists = await User.exists({ email: 'john@example.com' });
// Returns { _id: '...' } if exists, null if not
// Use in conditionals
if (await User.exists({ email: 'john@example.com' })) {
console.log('User already exists!');
}
✏️ UPDATE Methods
1. Model.findByIdAndUpdate(id, update, options) - Update by ID
// Update user by ID
const updated = await User.findByIdAndUpdate(
'507f1f77bcf86cd799439011',
{ age: 29 }, // Update data
{ new: true } // Return updated document (default: returns old document)
);
// Returns the updated user
// With validation
const updated = await User.findByIdAndUpdate(
id,
{ age: 29 },
{
new: true, // Return updated document
runValidators: true // Run schema validators
}
);
2. Model.findOneAndUpdate(filter, update, options) - Update one
// Update by email
const updated = await User.findOneAndUpdate(
{ email: 'john@example.com' }, // Filter
{ age: 30 }, // Update
{ new: true } // Options
);
3. Model.updateOne(filter, update) - Update one (no return)
// Update one document (doesn't return the document)
await User.updateOne(
{ email: 'john@example.com' }, // Filter
{ $set: { age: 30 } } // Update operator
);
// Returns: { acknowledged: true, modifiedCount: 1 }
// Update operators:
// $set - Set field value
// $inc - Increment number
// $push - Add to array
// $pull - Remove from array
4. Model.updateMany(filter, update) - Update multiple
// Update all matching documents
await User.updateMany(
{ role: 'user' }, // Filter
{ $set: { isActive: true } } // Update
);
// Returns: { acknowledged: true, modifiedCount: 25 }
5. Instance .save() - Update existing document
How it works: When you find an existing document and modify it, calling .save() updates that same document in the database with the same _id. It does NOT create a new document.
// Step 1: Find an existing document (user already exists in database)
const user = await User.findById(id);
// user = { _id: "507f1f77bcf86cd799439011", name: "John", age: 28, ... }
// Step 2: Modify the document (changes are only in memory, not saved yet)
user.age = 29; // Change age from 28 to 29
user.name = 'John Updated'; // Change name from "John" to "John Updated"
// At this point, changes exist only in the 'user' variable, NOT in the database!
// Step 3: Save the changes to the database
await user.save();
// ✅ Updates the SAME document with the SAME _id in the database
// ✅ Does NOT create a new document
// ✅ Returns the updated document
// Result in database:
// Same document, updated fields:
// { _id: "507f1f77bcf86cd799439011", name: "John Updated", age: 29, ... }
// ↑ Same ID ↑ Updated values
- Same
_id: The document keeps its original_id- it's an UPDATE, not a CREATE - No new document:
.save()on an existing document updates it in place - All changes saved: Only the fields you modify are updated; other fields remain unchanged
- Validation runs: Schema validators are automatically checked before saving
user.save()on an existing document → UPDATES the same documentnew User({...}).save()on a new instance → CREATES a new document
// Comparison Example:
// UPDATE existing document (same _id)
const existingUser = await User.findById('507f1f77bcf86cd799439011');
// existingUser._id = "507f1f77bcf86cd799439011" (already has an ID)
existingUser.age = 30;
await existingUser.save();
// ✅ Updates document with _id "507f1f77bcf86cd799439011"
// CREATE new document (new _id)
const newUser = new User({ name: 'Jane', age: 25 });
// newUser._id = undefined (no ID yet - new document)
await newUser.save();
// ✅ Creates NEW document with a NEW _id (e.g., "507f1f77bcf86cd799439012")
🗑️ DELETE Methods
1. Model.findByIdAndDelete(id) - Delete by ID
// Delete user by ID
const deleted = await User.findByIdAndDelete('507f1f77bcf86cd799439011');
// Returns the deleted document or null
2. Model.findOneAndDelete(filter) - Delete one
// Delete by email
const deleted = await User.findOneAndDelete({ email: 'john@example.com' });
// Returns the deleted document or null
3. Model.deleteOne(filter) - Delete one (no return)
// Delete one document (doesn't return the document)
await User.deleteOne({ email: 'john@example.com' });
// Returns: { acknowledged: true, deletedCount: 1 }
4. Model.deleteMany(filter) - Delete multiple
// Delete all matching documents
await User.deleteMany({ isActive: false });
// Returns: { acknowledged: true, deletedCount: 10 }
// Deletes all inactive users
📊 Method Summary Table
| Category | Method | Returns |
|---|---|---|
| CREATE | Model.create(data) |
Created document(s) |
new Model(data).save() |
Saved document | |
| READ | Model.find(filter) |
Array of documents |
Model.findOne(filter) |
Document or null | |
Model.findById(id) |
Document or null | |
Model.countDocuments(filter) |
Number | |
Model.exists(filter) |
{ _id } or null |
|
.select(), .sort(), .limit(), .skip() |
Query chain | |
| UPDATE | Model.findByIdAndUpdate(id, update) |
Updated document |
Model.findOneAndUpdate(filter, update) |
Updated document | |
Model.updateOne(filter, update) |
Update result | |
Model.updateMany(filter, update) |
Update result | |
instance.save() |
Saved document | |
| DELETE | Model.findByIdAndDelete(id) |
Deleted document |
Model.findOneAndDelete(filter) |
Deleted document | |
Model.deleteOne(filter) |
Delete result | |
Model.deleteMany(filter) |
Delete result |
Complete Example: Express + MongoDB
index.js - Main Server
// index.js
const express = require('express');
const connectDB = require('./db');
const userRoutes = require('./routes/users');
const app = express();
// Connect to database
connectDB();
// Middleware
app.use(express.json());
// Routes
app.use('/api/users', userRoutes);
// Start server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
routes/users.js - User Routes
// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// GET /api/users - Get all users
router.get('/', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// GET /api/users/:id - Get one user
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// POST /api/users - Create user
router.post('/', async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// PUT /api/users/:id - Update user
router.put('/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true }
);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// DELETE /api/users/:id - Delete user
router.delete('/:id', async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User deleted' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
- MongoDB stores JSON-like documents in collections
- Mongoose provides schema validation and easy queries
- Always use
async/awaitwithtry/catch - Use
findById,findOne,findfor reading - Use
create,findByIdAndUpdate,findByIdAndDelete