𝗗𝗮𝘆 𝟰𝟯 𝗼𝗳 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗠𝗘𝗥𝗡 𝗦𝘁𝗮𝗰𝗸
I finished full CRUD operations today.
Yesterday I learned to read data using req.params. Today I learned to change data using HTTP POST, PUT, and DELETE methods. I used the file system to modify my local database.
Writing code that changes data requires care. You must manage the lifecycle to avoid corrupting your storage.
Here is how I built the POST route:
- I used express.json() middleware to read the incoming body.
- I created a new user object with a unique ID.
- I added the new user to the existing array.
- I used the fs module to save the updated array to my JSON file.
Here is the code:
const express = require("express"); const fs = require("fs"); const users = require("./MOCK_DATA.json"); const app = express();
app.use(express.json());
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 });
});
});
This step moves me from reading data to managing a full data lifecycle.
Source: https://dev.to/ali_hamza_589ec7b3eb6688d/day-43-of-learning-mern-stack-1cif