Creating a Route to Update Notes in Our CloudNoteBook App โ๏ธ๐
Every good Notes app needs a way to edit an existing note โ maybe the user wants to
fix a typo, change the title, or update the tag. In REST API terms, this means building an
Update Note API using the PUT HTTP method. In this part of our
CloudNoteBook App (built with Node.js, Express, and MongoDB), we'll create a secure
backend route that lets a logged-in user update only their own notes.
In this tutorial, we will learn:
PUT route is and when to use it/api/notes/updatenote/:id Express routefetchuser authentication middleware_idfindByIdAndUpdate methodWhat is an Update Note API Route?
In REST APIs, each HTTP method maps to an action: GET reads data, POST
creates data, PUT updates data, and DELETE removes data. Since we're
modifying an existing note rather than creating a new one, the correct choice is a
PUT route. Our route will accept the note's id as a URL parameter and the
new title, description, and tag in the request body.
Step 1: Import Required Modules in notes.js
Open routes/notes.js in your CloudNoteBook backend and make sure the
Note model and fetchuser middleware are already imported, since
we'll reuse both of them for this route.
const express = require("express");
const router = express.Router();
const fetchuser = require("../middleware/fetchuser");
const Note = require("../models/Note");
Step 2: Define the PUT Route for Updating a Note
Let's create ROUTE 3: PUT "/api/notes/updatenote/:id". This route is
protected by fetchuser, meaning only a logged-in user with a valid auth token can
access it.
// ROUTE 3: Update an existing note using: PUT "/api/notes/updatenote/:id". Login required
router.put("/updatenote/:id", fetchuser, async (req, res) => {
const { title, description, tag } = req.body;
try {
// Create a newNote object with only the fields that were sent
const newNote = {};
if (title) { newNote.title = title; }
if (description) { newNote.description = description; }
if (tag) { newNote.tag = tag; }
// We'll find and update the note in the next step
res.json({ newNote });
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
Step 3: Find the Note and Check Ownership
Before updating anything, we must confirm two things: the note with the given id
actually exists, and it belongs to the logged-in user. Skipping this check would let
any logged-in user update someone else's notes โ a serious security flaw.
let note = await Note.findById(req.params.id);
if (!note) {
return res.status(404).send("Not Found");
}
if (note.user.toString() !== req.user.id) {
return res.status(401).send("Not Allowed");
}
Step 4: Update the Note Using findByIdAndUpdate
Once ownership is confirmed, we use Mongoose's findByIdAndUpdate method to update
the note in MongoDB and return the updated document using the { new: true }
option.
note = await Note.findByIdAndUpdate(
req.params.id,
{ $set: newNote },
{ new: true }
);
res.json({ note });
Step 5: Full Updated Update Note Route
Here is the complete PUT /api/notes/updatenote/:id route with the ownership check
and update logic combined.
// ROUTE 3: Update an existing note using: PUT "/api/notes/updatenote/:id". Login required
router.put("/updatenote/:id", fetchuser, async (req, res) => {
const { title, description, tag } = req.body;
try {
// Create a newNote object with only the fields that were sent
const newNote = {};
if (title) { newNote.title = title; }
if (description) { newNote.description = description; }
if (tag) { newNote.tag = tag; }
// Find the note to be updated
let note = await Note.findById(req.params.id);
if (!note) {
return res.status(404).send("Not Found");
}
// Allow update only if the logged-in user owns this note
if (note.user.toString() !== req.user.id) {
return res.status(401).send("Not Allowed");
}
note = await Note.findByIdAndUpdate(
req.params.id,
{ $set: newNote },
{ new: true }
);
res.json({ note });
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
module.exports = router;
Testing the Update Note API with Postman
To test this route, open Postman and send a PUT request to
http://localhost:5000/api/notes/updatenote/<note_id>. Add your auth-token
header from login, and in the body (JSON), pass only the fields you want to change, for example:
{ "title": "Updated Title" }. You should get back the updated note object in the response.
Update Note API โ Response Status Codes
| Status Code | Meaning | When It Happens |
|---|---|---|
200 OK |
Success | Note found, owned by the user, and successfully updated |
401 Not Allowed |
Unauthorized | The note exists but belongs to a different user |
404 Not Found |
Note doesn't exist | No note matches the given id in MongoDB |
500 Internal Server Error |
Server-side failure | Database connection issue or unexpected exception |
Features and Learnings:-
PUT method is used to update existing resources./api/notes/updatenote/:id route protected by fetchuser.findById.findByIdAndUpdate with { new: true } to return the updated document.