Handling Routes, Middleware, and MongoDB Guide
6. Handling Routes, Route, and Query Parameters
a) Handling Routes
Routing determines how an application responds to client requests. A route defines a URL pattern
and a function that executes when a request matches the pattern.
Example:
app.get('/', (req, res) => { res.send('Home Page'); });
b) Route Parameters
Route parameters are dynamic segments in a URL, used to capture values.
Example:
app.get('/user/:id', (req, res) => { res.send(`User ID: ${req.params.id}`); });
c) Query Parameters
Query parameters are key-value pairs appended to the URL after a question mark.
Example:
app.get('/search', (req, res) => { res.send(`Searching for: ${req.query.keyword}`); });
7. Middleware and CSS Preprocessor
i) Helmet Middleware
Helmet is an Express.js middleware that enhances security by setting HTTP headers.
Example:
const helmet = require('helmet');
app.use(helmet());
ii) Stylus CSS Pre-processor
Stylus is a CSS pre-processor that simplifies styling.
Example:
body
background-color #f5f5f5
8. MongoDB Structure and Architecture
a) MongoDB Structure
- Database: Contains collections.
- Collection: Contains documents.
- Document: JSON-like structure.
Example:
"_id": ObjectId("605c72d1f3a1c4b7f0a21c5b"),
"name": "John Doe",
"age": 30
}
b) MongoDB Architecture
1. Sharded Cluster
2. Replication Set
3. Mongos Router
4. Config Servers
9. MongoDB Shell JavaScript Engine
The MongoDB Shell (mongosh) is an interactive JavaScript interface.
Example:
use myDatabase
db.users.insertOne({ name: "Alice", age: 25 })
db.users.find()
10. Creating, Deleting Databases and Collections in MongoDB
a) Creating a Database:
use myDatabase
b) Creating a Collection:
db.createCollection("users")
c) Deleting a Collection:
db.users.drop()
d) Deleting a Database:
db.dropDatabase()