📅 Date: June 25, 2026
🧠Mood: The Data Wrangler 📊
🔥 Topic: Web Dev Day 20: Express Backend & MongoDB Aggregation
⚙️ Forging the Backend Engine
With the architecture set, today was all about wiring up the backend for CineMetrics. I initialized my package.json, installed Express and Mongoose, and secured my connection strings using environment variables (.env).
Building the basic CRUD endpoints (POST, GET, PATCH) was straightforward. The real engineering challenge was satisfying the analytics requirement of my PRD. I needed to extract the Top Genre and Average Rating from the database. Instead of pulling all the data into my Node.js server and filtering it with loops—which is terrible for performance—I utilized MongoDB Aggregation Pipelines to make the database do the heavy lifting.
🗄️ The Aggregation Pipeline
An aggregation pipeline processes data through multiple stages, passing the results from one stage directly into the next. Here is how I built the /api/movies/analytics endpoint controller.
// controllers/analyticsController.js
const Movie = require('../models/Movie');
exports.getAnalytics = async (req, res) => {
try {
const stats = await Movie.aggregate([
// Stage 1: Filter out unwatched movies
{ $match: { isWatched: true } },
// Stage 2: Deconstruct the genre array so each genre gets its own document
{ $unwind: "$genre" },
// Stage 3: Group by genre, count them, and average the ratings
{
$group: {
_id: "$genre",
count: { $sum: 1 },
avgRating: { $avg: "$rating" }
}
},
// Stage 4: Sort by the most watched genre (descending)
{ $sort: { count: -1 } },
// Stage 5: Only keep the absolute top genre
{ $limit: 1 }
]);
res.status(200).json({ success: true, data: stats });
} catch (error) {
res.status(500).json({ success: false, error: "Server Error" });
}
};
⚠️ Routing Hierarchy Warning
One massive bug I encountered was Endpoint Collision. I initially placed my /api/movies/:id route above my /api/movies/analytics route in the code. Express mistakenly thought the word "analytics" was a dynamic movie ID, causing a server crash. Remember to always place static routes above dynamic parameter routes!
🎯 Backend Secured
The RESTful API is now fully operational and securely handling complex data queries via Mongoose. Tomorrow, we open the cinemetrics-frontend folder to build the dashboard UI and connect it to our server using Vanilla JavaScript.
No comments:
Post a Comment