Day 79

CRUD Operations — Complete

13 min
JavaScript 100 Days

Complete CRUD application banate hain — Express routes + Mongoose models + relationships + pagination. Real production API kaisa hota hai yeh samjho.

Full CRUD Controller

Structured CRUD controller pattern.

product-controller.js
javascript
const Product = require("../models/Product");

const productController = {
  // GET /products — all with pagination
  async getAll(req, res) {
    try {
      const { page = 1, limit = 10, category, sort = "createdAt" } = req.query;
      const skip = (page - 1) * limit;
      
      const query = category ? { category } : {};
      
      const [products, total] = await Promise.all([
        Product.find(query)
          .sort({ [sort]: -1 })
          .skip(skip)
          .limit(parseInt(limit))
          .populate("category", "name"),
        Product.countDocuments(query)
      ]);
      
      res.json({
        data: products,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      });
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  },
  
  async create(req, res) {
    try {
      const product = await Product.create(req.body);
      res.status(201).json({ success: true, data: product });
    } catch (err) {
      if (err.name === "ValidationError") {
        return res.status(422).json({ 
          error: "Validation failed",
          details: Object.values(err.errors).map(e => e.message)
        });
      }
      res.status(500).json({ error: err.message });
    }
  }
};

module.exports = productController;

🎯 Practice Challenge

E-commerce API banao — Products, Categories, Orders. Proper pagination, filtering, sorting, aur related data populate karo.