Creating a Route to Delete Notes in CloudNoteBook App ๐๏ธ๐
So far, our CloudNoteBook App lets users add, fetch, and update their personal notes.
But every notebook app needs a way to delete a note the user no longer needs.
In this part, we'll build a secure DELETE route using Express.js and Mongoose,
making sure a user can only delete their own notes โ not anyone else's.
In this tutorial, we will learn:
DELETE HTTP method/api/notes/deletenote/:id endpoint in Expressfetchuser authentication middlewareNotes.findById()Notes.findByIdAndDelete()What is a DELETE Route in a REST API?
In REST API design, the DELETE HTTP method is used to remove a specific resource โ
in our case, a single note. A well-designed delete route doesn't just remove data blindly;
it checks who is making the request and whether that note belongs to them before
deleting anything. This keeps every user's notes private and safe from other logged-in users.
Step 1: Set Up the Route Skeleton
Open your routes/notes.js file. We'll add a new route using router.delete(),
protected by the existing fetchuser middleware (the same one used in addnote
and updatenote) so only logged-in users can reach it.
const express = require("express");
const router = express.Router();
const fetchuser = require("../middleware/fetchuser");
const Notes = require("../models/Notes");
// ROUTE 4: Delete an existing note using: DELETE "/api/notes/deletenote/:id". Login required
router.delete("/deletenote/:id", fetchuser, async (req, res) => {
// Logic goes here
});
module.exports = router;
Step 2: Find the Note by ID
Before deleting anything, we must confirm the note actually exists. We use
Notes.findById(), passing in the id from the route parameter.
router.delete("/deletenote/:id", fetchuser, async (req, res) => {
try {
let note = await Notes.findById(req.params.id);
if (!note) {
return res.status(404).send("Note Not Found");
}
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
Step 3: Verify Note Ownership
This is the most important security check. Every note stores the user field โ
the ID of whoever created it. We compare that against req.user.id, which
fetchuser attaches from the logged-in user's JWT token. If they don't match,
we block the request with a 401 Unauthorized response.
// Allow deletion only if the note belongs to the logged-in user
if (note.user.toString() !== req.user.id) {
return res.status(401).send("Not Allowed");
}
Step 4: Delete the Note with findByIdAndDelete
Once ownership is confirmed, we remove the note from MongoDB using Mongoose's
findByIdAndDelete() method and send the deleted note back as a response.
note = await Notes.findByIdAndDelete(req.params.id);
res.json({ success: "Note has been deleted", note: note });
Step 5: Full Updated Delete Route
Here is the complete deletenote route combined, ready to be added to your
existing routes/notes.js file alongside addnote, fetchallnotes,
and updatenote.
const express = require("express");
const router = express.Router();
const fetchuser = require("../middleware/fetchuser");
const Notes = require("../models/Notes");
// ROUTE 4: Delete an existing note using: DELETE "/api/notes/deletenote/:id". Login required
router.delete("/deletenote/:id", fetchuser, async (req, res) => {
try {
// Find the note to be deleted
let note = await Notes.findById(req.params.id);
if (!note) {
return res.status(404).send("Note Not Found");
}
// Allow deletion only if the note belongs to the logged-in user
if (note.user.toString() !== req.user.id) {
return res.status(401).send("Not Allowed");
}
note = await Notes.findByIdAndDelete(req.params.id);
res.json({ success: "Note has been deleted", note: note });
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
module.exports = router;
Testing the Delete Route in Postman
Open Postman and send a DELETE request to http://localhost:5000/api/notes/deletenote/<note_id>,
with an auth-token header containing a valid JWT. If the note exists and belongs to
the logged-in user, you'll receive a success message along with the deleted note's data.
How the Delete Route Behaves
| Scenario | Response | Reason |
|---|---|---|
| No auth token sent | 401 Unauthorized |
Blocked by fetchuser middleware before reaching the route logic |
| Note ID doesn't exist | 404 Not Found |
findById() returns null |
| Note belongs to a different user | 401 Not Allowed |
note.user doesn't match req.user.id |
| Note exists and belongs to the user | 200 OK + deleted note |
findByIdAndDelete() removes it successfully |
Features and Learnings:-
DELETE HTTP method is used in REST API design./api/notes/deletenote/:id route in Express.js.fetchuser authentication middleware.Notes.findById() to check whether a note exists before deleting it.Notes.findByIdAndDelete() to remove the note from MongoDB.401, 404, 500) for different error cases.auth-token header.