Update operation in an Express.js application using EJS and Mongoose
To implement an update operation in an Express.js application using EJS and Mongoose, you need to create functionality for displaying an edit form, handling form submissions to update a record, and reflecting these changes in your database. Below is a step-by-step guide to setting up the update operation:
1. Set Up Your Project
Ensure your project has Express, Mongoose, and EJS installed and configured. If you haven’t set up your project yet, follow the initialization steps provided in the previous guide.
2. Define Mongoose Model
You should have a Mongoose model defined for your data. For this example, we'll use 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 set up routes to handle displaying the edit form and updating the record.
app.js
Route to Display the Edit Form:
This route will fetch the item from the database and render an EJS template with a form to edit the item.
app.get('/items/edit/:id', async (req, res) => { try { const item = await Item.findById(req.params.id); if (!item) { return res.status(404).send('Item not found'); } res.render('edit', { item }); } catch (err) { console.error(err); res.status(500).send('Server Error'); } });
Route to Handle Form Submission for Updating:
This route will process the form data and update the item in the database.
app.post('/items/:id', async (req, res) => { try { const { name, description } = req.body; await Item.findByIdAndUpdate(req.params.id, { name, description }, { new: true }); res.redirect('/'); } catch (err) { console.error(err); res.status(500).send('Server Error'); } });
4. Create EJS Templates
Create
views/edit.ejs
:This template will display the form to edit an item. It pre-fills the form with the current values of the item.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit Item</title> </head> <body> <h1>Edit Item</h1> <form action="/items/<%= item._id %>" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= item.name %>" required> <br> <label for="description">Description:</label> <textarea id="description" name="description"><%= item.description %></textarea> <br> <button type="submit">Update Item</button> </form> <a href="/">Back to Items List</a> </body> </html>
Modify
views/index.ejs
to Include Edit Links:Ensure that your list view allows users to navigate to the edit form.
<!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 Update Operation
Start the Server:
node app.js
Navigate to the Edit Form:
- Open your browser and go to
http://localhost:3000
to view the list of items. - Click on the “Edit” link next to an item to navigate to the edit form.
- Open your browser and go to
Update the Item:
- Make changes to the item in the form and submit it.
- Verify that the item is updated by checking the list of items.
Summary
- Set Up Routes: Implement routes to display the edit form and handle updates.
- Create EJS Templates: Build the form for editing and update the item in the database.
- Test the Operation: Ensure that the update functionality works correctly by testing it in your application.