0
0
Expressframework~30 mins

Deleting documents in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Deleting Documents with Express
📖 Scenario: You are building a simple web server using Express. This server manages a list of documents stored in memory. You want to add the ability to delete a document by its ID.
🎯 Goal: Build an Express server that stores documents in an array and allows deleting a document by its id using a DELETE request.
📋 What You'll Learn
Create an array called documents with three objects, each having id and title properties.
Create a variable called deleteId and set it to 2.
Use the filter method on documents to remove the document with id equal to deleteId.
Add an Express DELETE route at /documents/:id that deletes the document with the given id from documents.
💡 Why This Matters
🌍 Real World
Deleting documents or records is a common feature in web applications like content management systems, note-taking apps, or admin dashboards.
💼 Career
Understanding how to handle DELETE requests and manipulate data collections is essential for backend developers working with REST APIs.
Progress0 / 4 steps
1
Create the initial documents array
Create an array called documents with these exact objects: { id: 1, title: 'Doc One' }, { id: 2, title: 'Doc Two' }, and { id: 3, title: 'Doc Three' }.
Express
Need a hint?

Use const documents = [ ... ] with three objects inside.

2
Set the ID to delete
Create a variable called deleteId and set it to the number 2.
Express
Need a hint?

Use const deleteId = 2; to store the ID to delete.

3
Filter out the document to delete
Use the filter method on documents to create a new array without the document whose id equals deleteId. Assign this new array back to documents.
Express
Need a hint?

Use documents = documents.filter(doc => doc.id !== deleteId); to remove the document.

4
Add Express DELETE route to delete documents
Add an Express DELETE route at /documents/:id. Inside the route, convert req.params.id to a number, then update documents by filtering out the document with that id. Send a JSON response with { message: 'Document deleted' }.
Express
Need a hint?

Use app.delete('/documents/:id', (req, res) => { ... }) and inside convert req.params.id to a number, then filter documents, then send JSON response.