🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

Updating & Deleting (CRUD)

Complete your mastery of server-side CRUD operations. Learn how to execute Updates using `req.params` and `req.body`, and understand the critical architectural difference between Hard Deletes and Soft Deletes.

Narrated Video Summary
data-composition-id="apicreationmanipulation-module4_lesson11"1280×720 @ 30fps5 clips2:27 total

Executing CRUD: Update

We have learned how to Read (GET) and Create (POST) data. Now, we must implement Update functionality. In Express, we handle this using a PUT or PATCH route. The route requires two things: a URL parameter (to know WHICH record to update) and a JSON body (to know WHAT the new data is). We use both `req.params` and `req.body` simultaneously to tell our ORM exactly what to modify in the database.

// 🔄 Update (PATCH)

app.patch('/users/:id', async (req, res) => {
  const targetId = parseInt(req.params.id);
  const newEmail = req.body.email;

  // Wait for the ORM to execute the update...
});

ORM Update Syntax

Using an ORM like Prisma, updating a record is straightforward. You call `prisma.user.update()`. This method takes an object with two critical properties: `where` and `data`. The `where` object acts as the filter, telling the database exactly which row to target (using `req.params.id`). The `data` object provides the new values that should overwrite the existing data (using `req.body`).

// 📝 Executing the Update

const updatedUser = await prisma.user.update({
  where: { id: parseInt(req.params.id) },
  data: req.body
});

res.status(200).json(updatedUser);

Executing CRUD: Delete

The final operation is Delete. A DELETE request is much simpler than an Update because it does not require a request body. The server only needs to know WHICH record to destroy. Therefore, you only need to extract the target ID from `req.params`. Once you have the ID, you pass it to your ORM's delete method. Finally, you return a success message or a 204 No Content status code.

// 🗑️ Delete (DELETE)

app.delete('/users/:id', async (req, res) => {
  const targetId = parseInt(req.params.id);

  // Delete from Database
  await prisma.user.delete({
    where: { id: targetId }
  });

  res.json({ message: "User deleted" });
});

Soft vs Hard Deletes

In the real world, running a `DELETE` SQL command (a 'Hard Delete') is extremely dangerous. If a user deletes their account, and you hard delete them, you permanently break all data related to them (like their past orders or forum posts). Instead, professional APIs use 'Soft Deletes'. Rather than actually deleting the row from the database, you run an UPDATE command that sets a boolean flag: `isDeleted = true`. The data remains safe, but is hidden from the UI.

// 👻 Soft Delete Approach

// We don't use .delete()
// We use .update() to hide the record.

await prisma.user.update({
  where: { id: 42 },
  data: { isDeleted: true }
});

CRUD Mastery

You have now mastered the implementation of all four CRUD operations on a real Express backend. You can Create, Read, Update, and Delete data using an ORM. However, we have been assuming that the client always sends perfect data. In reality, clients send garbage data. In the next module, we will learn how to defend our database by implementing Backend Validation.

/* CRUD Complete */
.curriculum { next: 'backend_validation'; }
0:00 / 2:27
Scene 1 / 5 — Executing CRUD: Update
Total XP: 0|💻 apicreationmanipulation XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

Updates & Deletes

Modify records.

Quick Quiz //

Why does an Update (PATCH) route typically require you to extract data from both `req.params` and `req.body`?


🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Modifying and destroying data are the most dangerous operations in an API. They must be handled with precision and safety.

1The Complexity of Updates

Updating a record is logically the most complex of the four CRUD operations because it requires the intersection of two data streams. You must extract the Target ID from the URL (req.params) to locate the specific record in the database. Simultaneously, you must extract the Payload from the request body (req.body) to know what new data to apply. If you mix these up, you might accidentally overwrite the wrong user's profile.

+
// Implementation Example

async function execute() {
  // See concept above
}
localhost:3000
localhost:3000
Status: Execution verified and active.

2Coding PATCH vs PUT

In a previous module, we learned that PUT is a full replacement and PATCH is a partial update. In your Express code, this translates directly to how you configure your ORM. If your route is a PUT, you must write logic to overwrite every single field in the database, setting missing fields to null. If your route is a PATCH, you simply pass req.body directly to the ORM, allowing it to dynamically update only the specific fields provided by the client.

+
// Implementation Example

async function execute() {
  // See concept above
}
localhost:3000
localhost:3000
Status: Execution verified and active.

3The Soft Delete Architecture

Data is the most valuable asset a company has. You never truly delete it. If a user deletes their account, executing a raw SQL DELETE command destroys the relational integrity of the database. All of their past orders, comments, and analytics become 'orphaned', causing the app to crash when it tries to load them. Instead, a 'DELETE' route in Express should actually execute an ORM update() command, flipping a boolean column called isDeleted or isActive. Your GET routes are then modified to filter out any users where isDeleted is true.

+
// Implementation Example

async function execute() {
  // See concept above
}
localhost:3000
localhost:3000
Status: Execution verified and active.

4Step-by-Step Breakdown

Executing CRUD: Update. We have learned how to Read (GET) and Create (POST) data. Now, we must implement Update functionality. In Express, we handle this using a PUT or PATCH route. The route requires two things: a URL parameter (to know WHICH record to update) and a JSON body (to know WHAT the new data is). We use both req.params and req.body simultaneously to tell our ORM exactly what to modify in the database.

ORM Update Syntax. Using an ORM like Prisma, updating a record is straightforward. You call prisma.user.update(). This method takes an object with two critical properties: where and data. The where object acts as the filter, telling the database exactly which row to target (using req.params.id). The data object provides the new values that should overwrite the existing data (using req.body).

When writing an Update route in Express, why is it usually necessary to access both req.params and req.body?

  • Because you need req.params to identify WHICH specific record to update, and req.body to know WHAT new data to apply to it.
  • Because Express throws an error if you don't use both.

Executing CRUD: Delete. The final operation is Delete. A DELETE request is much simpler than an Update because it does not require a request body. The server only needs to know WHICH record to destroy. Therefore, you only need to extract the target ID from req.params. Once you have the ID, you pass it to your ORM's delete method. Finally, you return a success message or a 204 No Content status code.

Soft vs Hard Deletes. In the real world, running a DELETE SQL command (a 'Hard Delete') is extremely dangerous. If a user deletes their account, and you hard delete them, you permanently break all data related to them (like their past orders or forum posts). Instead, professional APIs use 'Soft Deletes'. Rather than actually deleting the row from the database, you run an UPDATE command that sets a boolean flag: isDeleted = true. The data remains safe, but is hidden from the UI.

Why do enterprise APIs almost exclusively use 'Soft Deletes' (setting a flag like isActive: false) instead of actually deleting rows from the database?

  • Because permanently deleting a row can break relational data (e.g., deleting a user leaves 'orphan' records of their past purchases).
  • Because deleting data costs more money in server fees.

CRUD Mastery. You have now mastered the implementation of all four CRUD operations on a real Express backend. You can Create, Read, Update, and Delete data using an ORM. However, we have been assuming that the client always sends perfect data. In reality, clients send garbage data. In the next module, we will learn how to defend our database by implementing Backend Validation.

Level Up 🚀

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Semantic Usage

Using the proper structure for Executing CRUD: Update ensures that screen readers can correctly interpret the content hierarchy and purpose.

<!-- Apply semantic elements appropriately -->

SEO Implications

  • 1

    Contextual Relevance

    Proper implementation of Executing CRUD: Update provides search engine crawlers with better context, improving the indexing accuracy of your page.

Best Practices

Clean Code

Always validate your structure when using Executing CRUD: Update to prevent layout shifts and DOM inconsistencies.

Separation of Concerns

Keep styling and behavior separate from the structural markup of Executing CRUD: Update.

Frequent Bugs

THE BUG

Unexpected layout shifts or styling failures.

THE FIX

Ensure all implementations related to Executing CRUD: Update are properly structured according to strict specifications.

Real-World Examples

Production Usage

Here is how Executing CRUD: Update is typically implemented in a professional, robust application.

<!-- Best practice implementation of Executing CRUD: Update -->
<div class="production-ready">
  <!-- Content -->
</div>

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Not reading error messages carefully

Uncaught TypeError: Cannot read properties of undefined (reading 'length') // Solution: Ensure the variable you are calling .length on is initialized as a string or an array, not undefined.

The Solution //

Most of the time, the compiler or interpreter tells you exactly what line caused the crash and why. Read stack traces from the top down to identify the root cause.

The Error //

Hardcoding sensitive credentials

// Wrong const API_KEY = 'sk-123456789'; // Correct const API_KEY = process.env.API_KEY;

The Solution //

Never hardcode API keys, passwords, or secrets in your source code. Use environment variables (.env files) to keep them secure and out of version control.

Lesson Glossary

[01]PATCH

An HTTP method used to apply partial modifications to a resource.

Code Preview
The Modifier

[02]DELETE

An HTTP method used to request the removal of a specific resource from the server.

Code Preview
The Destroyer

[03]Hard Delete

A database operation that permanently and irrevocably removes a record from the storage disk. Dangerous for relational data.

Code Preview
Permanent Erasure

[04]Soft Delete

An architectural pattern where a record is not physically deleted, but instead marked as inactive (e.g., isDeleted = true) so it is hidden from the user interface.

Code Preview
The Hidden Flag

[05]HTTP 204

No Content. A common success status code for a DELETE operation, indicating the action succeeded but there is no data to send back.

Code Preview
Success, Nothing to Return

Continue Learning