Delete operation in an Express.js application using EJS and Mongoose


To implement a delete operation in an Express.js application using EJS and Mongoose, you need to set up functionality to handle deleting a record from the MongoDB database and reflecting those changes in your application. Here’s a step-by-step guide:

1. Set Up Your Project

Ensure your project has Express, Mongoose, and EJS installed and configured. If not, refer to the setup steps provided in previous guides.

2. Define Mongoose Model

Assuming you have a Mongoose model set up for your data, such as the Item model:

models/Item.js

const mongoose = require('mongoose'); const itemSchema = new mongoose.Schema({ name: { type: String, required: true }, description: String }); const Item = mongoose.model('Item', itemSchema); module.exports = Item;

3. Set Up Express Routes

You need to create routes to handle displaying the items and processing the delete requests.

app.js

  1. Route to Handle Deleting an Item:

    This route will process the delete request and remove the item from the database.

    app.post('/items/delete/:id', async (req, res) => { try { await Item.findByIdAndDelete(req.params.id); res.redirect('/'); } catch (err) { console.error(err); res.status(500).send('Server Error'); } });
  2. Route to Display All Items (for testing purposes):

    This route will list all items and include a form to delete each item.

    app.get('/', async (req, res) => { try { const items = await Item.find(); res.render('index', { items }); } catch (err) { console.error(err); res.status(500).send('Server Error'); } });

4. Create EJS Templates

  1. Create views/index.ejs:

    This template displays the list of items and includes a form for deleting each item.

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Items List</title> </head> <body> <h1>Items</h1> <a href="/items/new">Add New Item</a> <ul> <% items.forEach(item => { %> <li> <strong><%= item.name %></strong>: <%= item.description %> <a href="/items/edit/<%= item._id %>">Edit</a> <form action="/items/delete/<%= item._id %>" method="POST" style="display:inline;"> <button type="submit">Delete</button> </form> </li> <% }) %> </ul> </body> </html>

5. Test the Delete Operation

  1. Start the Server:

    node app.js
  2. Navigate to the List of Items:

    • Open your browser and go to http://localhost:3000 to view the list of items.
  3. Delete an Item:

    • Click the “Delete” button next to an item. This will send a POST request to delete that item.
    • Verify that the item is removed from the list.

Summary

  1. Set Up Routes: Implement routes to handle delete requests and display items.
  2. Create EJS Templates: Build views to list items and include delete functionality.
  3. Test the Operation: Ensure that the delete functionality works correctly by testing it in your application.