DEV Community

Ali Hamza
Ali Hamza

Posted on

Day 43 of Learning MERN Stack

Hello Dev Community! 👋

It is officially Day 43 of my journey to master the MERN stack! Yesterday, I engineered standard REST read routes using req.params. Today, I advanced to the absolute climax of this local database track inside Prashant Sir's (Complete Coding) backend masterclass: Completing full CRUD operations with file-system mutations.

I transitioned from simply displaying records to actively modifying my storage layers using HTTP POST, PUT, and DELETE methods!


🧠 Key Learnings From Node.js Lecture 11 (CRUD Mutations)

Writing state-altering code requires strict lifecycle management to prevent storage corruption. Here is how I structured my data pipelines today:

1. Ingesting Payloads (POST /api/users)

To append a new user, I grabbed the incoming body payload via middleware. I dynamically calculated a fresh unique identifier (users.length + 1), pushed the new record into our existing array object, and utilized the native fs module to overwrite the local data file asynchronously:


javascript
const express = require("express");
const fs = require("fs");
const users = require("./MOCK_DATA.json");
const app = express();

app.use(express.json()); // Essential body parser

app.post("/api/users", (req, res) => {
    const body = req.body;
    const newUser = { ...body, id: users.length + 1 };
    users.push(newUser);

    fs.writeFile("./MOCK_DATA.json", JSON.stringify(users), (err) => {
        if (err) return res.status(500).json({ error: "Write operation failed" });
        return res.status(201).json({ status: "Success", userId: newUser.id });
    });
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)