Create and Read Operation using Express.js, EJS, and Mongoose
Creating a new record in a MongoDB database using Express.js, EJS, and Mongoose involves setting up a form to collect user input, handling the form submission to create a new record in the database, and then displaying a confirmation or redirecting the user. Here’s a step-by-step guide:
1. Set Up Your Project
Ensure you have a basic Express.js application set up with Mongoose and EJS. If not, follow these steps to initialize it:
Initialize the Project:
mkdir express-crud-app cd express-crud-app npm init -y
Install Required Packages:
npm install express mongoose ejs body-parser
2. Define Mongoose Model
Create a schema and model to represent the data you want to store. For this example, we'll use an Item
model.
Create
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 Application
Create
app.js
:const express = require('express'); const mongoose = require('mongoose'); const path = require('path'); const bodyParser = require('body-parser'); const app = express(); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/crud-app', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('Connected to MongoDB'); }).catch(err => { console.error('Failed to connect to MongoDB', err); }); // Middleware app.use(bodyParser.urlencoded({ extended: true })); app.use(express.json()); // Set view engine to EJS app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Import Item model const Item = require('./models/Item'); // Route to display form to create a new item app.get('/items/new', (req, res) => { res.render('new'); }); // Route to handle form submission for creating a new item app.post('/items', async (req, res) => { try { const newItem = new Item(req.body); await newItem.save(); res.redirect('/'); } catch (err) { console.error(err); res.status(500).send('Server Error'); } }); // Route to display all items (for testing purposes) 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'); } }); // Start the server app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
4. Create EJS Templates
Create
views/new.ejs
:This template displays the form for creating a new item.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add New Item</title> </head> <body> <h1>Add New Item</h1> <form action="/items" method="POST"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <br> <label for="description">Description:</label> <textarea id="description" name="description"></textarea> <br> <button type="submit">Add Item</button> </form> <a href="/">Back to Items List</a> </body> </html>
Create
views/index.ejs
:This template displays the list of items.
<!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 %> </li> <% }) %> </ul> </body> </html>
5. Test the Create Operation
Start the Server:
Run your application using:
node app.js
Add a New Item:
- Open your browser and navigate to
http://localhost:3000/items/new
. - Fill out the form and submit it.
- Open your browser and navigate to
Verify the Creation:
- After submission, you should be redirected to
http://localhost:3000
, where you can see the newly added item listed.
- After submission, you should be redirected to
Summary
- Set Up the Project: Initialize the project and install dependencies.
- Define Mongoose Model: Create a schema and model for the data.
- Set Up Express Routes: Create routes to display the form and handle form submissions.
- Create EJS Templates: Build views for the form and item listing.
- Test the Operation: Verify that the create operation works by adding and displaying new items