Web Development with Coding
Databases with MongoDB
In This Section, You Will Learn:
- • Why databases are essential
- • SQL vs NoSQL databases
- • MongoDB – document-based database
- • Setting up MongoDB Atlas (cloud)
- • CRUD operations with Mongoose
- • Connecting your API to the database
Why You Need a Database
- Without a database, data disappears when the server restarts.
- Databases Store:
- • User accounts and profiles
- • Products and inventory
- • Orders and transactions
- • Messages and comments
- • Any data that needs to persist
- Two Main Types:
- • SQL (Relational): MySQL, PostgreSQL
- • NoSQL (Document): MongoDB
- We'll use MongoDB because:
- • Works naturally with JavaScript (JSON)
- • Flexible schema (no rigid structure)
- • Great for modern web applications
SQL vs NoSQL
- SQL (Structured Query Language):
- • Data in tables with rows and columns
- • Fixed schema (structure defined upfront)
- • Relationships between tables
- • Used by: Banks, traditional systems
- NoSQL (Not Only SQL):
- • Data as documents (like JSON objects)
- • Flexible schema (can change easily)
- • Great for rapid development
- • Used by: Startups, modern apps
- Example Document (MongoDB):
- “`
- {
- _id: ObjectId('…',
- name: 'Ahmed',
- email: 'ahmed@email.com',
- orders: [{ item: 'Laptop', price: 50000 }]
- }
- “`
- For beginners: Start with MongoDB, it's easier.
Setting Up MongoDB Atlas
- MongoDB Atlas is a free cloud database service.
- Setup Steps:
- 1. Create account at mongodb.com/atlas
- 2. Create a new cluster (free tier)
- 3. Create a database user (username/password)
- 4. Whitelist your IP address
- 5. Get your connection string
- Connection String:
- “`
- mongodb+srv://username:password@cluster.mongodb.net/database
- “`
- Store in .env File:
- “`
- MONGODB_URI=mongodb+srv://…
- “`
- Never commit passwords to GitHub!
Mongoose – ODM for MongoDB
- Mongoose makes working with MongoDB easier.
- Installing:
- “`
- npm install mongoose
- “`
- Connecting:
- “`
- const mongoose = require('mongoose');
- mongoose.connect(process.env.MONGODB_URI);
- “`
- Creating a Schema:
- “`
- const userSchema = new mongoose.Schema({
- name: { type: String, required: true },
- email: { type: String, unique: true },
- password: String,
- createdAt: { type: Date, default: Date.now }
- });
- const User = mongoose.model('User', userSchema);
- “`
- Schemas define the structure of documents.
CRUD Operations
- CRUD = Create, Read, Update, Delete
- Create:
- “`
- const newUser = new User({ name: 'Ahmed', email: 'a@b.com' });
- await newUser.save();
- // Or:
- await User.create({ name: 'Ahmed' });
- “`
- Read:
- “`
- const all = await User.find();
- const one = await User.findById(id);
- const filter = await User.find({ name: 'Ahmed' });
- “`
- Update:
- “`
- await User.findByIdAndUpdate(id, { name: 'New Name' });
- “`
- Delete:
- “`
- await User.findByIdAndDelete(id);
- “`
- These 4 operations cover 90% of database needs.