How To Build a Simple CRUD Application

ebook include PDF & Audio bundle (Micro Guide)

$12.99$7.99

Limited Time Offer! Order within the next:

We will send Files to your email. We'll never share your email with anyone else.

Building a simple CRUD (Create, Read, Update, Delete) application is a fundamental task for any web developer. CRUD operations form the backbone of most applications because they deal with the basic functions of managing data. Whether you're building a database-driven application or just want to understand how data is handled in the context of a web app, mastering these operations is essential.

In this article, we'll take a deep dive into creating a basic CRUD application. We'll discuss each of the operations, how they interact with the database, and how to implement them in a web application. By the end of this guide, you'll have a functional application that lets users perform all CRUD operations.

What is CRUD?

Before we dive into building a CRUD application, let's quickly review the four basic operations that the acronym CRUD represents:

  • Create: Add new records to the database.
  • Read: Retrieve and display records from the database.
  • Update: Modify existing records in the database.
  • Delete: Remove records from the database.

Most applications require some form of data manipulation, and CRUD operations are the most common way to manage this data. Let's walk through the steps of building a simple web-based CRUD application.

Tools and Technologies You Will Need

For this tutorial, we will use the following technologies:

  1. Backend: Node.js with Express for the server-side logic.
  2. Database: MongoDB for data storage (NoSQL).
  3. Frontend: HTML and JavaScript (client-side).
  4. Template Engine: EJS (Embedded JavaScript) for rendering views.
  5. Styling: Basic CSS to make the UI more user-friendly.

You can install Node.js and MongoDB on your local machine. Once you have Node.js installed, you can use npm (Node Package Manager) to install the necessary libraries.

npm install express mongoose ejs

Let's start building the CRUD application step by step.

Step 1: Set Up Your Project Structure

First, set up your project structure. You can create a new directory for your project and structure it like this:

├── views/
│   ├── index.ejs
│   ├── create.ejs
│   ├── edit.ejs
├── models/
│   └── Item.js
├── public/
│   └── style.css
├── app.js
└── package.json

Here's a breakdown of the folder structure:

  • views/: Contains the EJS files that will define the HTML views for our app.
  • models/: Contains the data model (in our case, the schema for items).
  • public/: Stores the static files, like stylesheets.
  • app.js: Main entry point for the Node.js server.
  • package.json: Defines the dependencies for the project.

Step 2: Initialize the Server with Express

In the app.js file, we will initialize the Express app, set up a connection to MongoDB, and configure routes for the CRUD operations.

const mongoose = require('mongoose');
const ejs = require('ejs');

const app = express();
const port = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/crudApp', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Define the item schema
const itemSchema = new mongoose.Schema({
  name: String,
  description: String,
});

// Create a model for the schema
const Item = mongoose.model('Item', itemSchema);

// Set EJS as the template engine
app.set('view engine', 'ejs');

// Middleware to parse incoming data
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));

// Home route to display all items
app.get('/', async (req, res) => {
  const items = await Item.find();
  res.render('index', { items });
});

// Route to create a new item
app.get('/create', (req, res) => {
  res.render('create');
});

// Route to handle form submission and create a new item
app.post('/create', async (req, res) => {
  const { name, description } = req.body;
  const newItem = new Item({ name, description });
  await newItem.save();
  res.redirect('/');
});

// Route to edit an item
app.get('/edit/:id', async (req, res) => {
  const item = await Item.findById(req.params.id);
  res.render('edit', { item });
});

// Route to handle updating an item
app.post('/edit/:id', async (req, res) => {
  const { name, description } = req.body;
  await Item.findByIdAndUpdate(req.params.id, { name, description });
  res.redirect('/');
});

// Route to delete an item
app.get('/delete/:id', async (req, res) => {
  await Item.findByIdAndDelete(req.params.id);
  res.redirect('/');
});

// Start the server
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Explanation of the Code:

  1. Setting up MongoDB : We use Mongoose to connect to MongoDB and define the schema for our data. The schema defines two fields: name and description.

  2. Routes:

    • GET /: Retrieves all items from the database and renders them on the homepage (index.ejs).
    • GET /create: Displays the form for creating a new item (create.ejs).
    • POST /create: Handles form submission and saves the new item to the database.
    • GET /edit/:id: Retrieves the item by ID and shows the form to edit it (edit.ejs).
    • POST /edit/:id: Updates the item in the database.
    • GET /delete/:id: Deletes the item from the database.

Step 3: Create EJS Views

Now, let's create the EJS templates to display the data and the forms for the Create, Update, and Delete operations.

views/index.ejs

This will display all the items in the database.

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CRUD Application</title>
  <link rel="stylesheet" href="/style.css">
</head>
<body>
  <h1>CRUD Application</h1>
  <a href="/create">Create New Item</a>
  <ul>
    <% items.forEach(item => { %>
      <li>
        <strong><%= item.name %></strong>: <%= item.description %>
        <a href="/edit/<%= item._id %>">Edit</a>
        <a href="/delete/<%= item._id %>">Delete</a>
      </li>
    <% }) %>
  </ul>
</body>
</html>

views/create.ejs

This is the form to create a new item.

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Create Item</title>
</head>
<body>
  <h1>Create New Item</h1>
  <form action="/create" method="POST">
    <label for="name">Name</label>
    <input type="text" id="name" name="name" required>
    <br>
    <label for="description">Description</label>
    <input type="text" id="description" name="description" required>
    <br>
    <button type="submit">Create</button>
  </form>
</body>
</html>

views/edit.ejs

This is the form to update an existing item.

<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="/edit/<%= 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>
    <input type="text" id="description" name="description" value="<%= item.description %>" required>
    <br>
    <button type="submit">Update</button>
  </form>
</body>
</html>

Step 4: Style the Application

Although styling is not essential for the functionality of the CRUD app, it helps make the interface more user-friendly. Add some basic CSS in the public/style.css file:

  font-family: Arial, sans-serif;
  padding: 20px;
}

h1 {
  color: #333;
}

a {
  text-decoration: none;
  color: #007BFF;
  margin-left: 10px;
}

ul {
  list-style-type: none;
}

form {
  max-width: 300px;
  margin-top: 20px;
}

input {
  width: 100%;
  padding: 8px;
  margin-bottom: 10px;
}

button {
  background-color: #007BFF;
  color: white;
  padding: 10px;
  border: none;
  cursor: pointer;
}

Step 5: Test the Application

To run your application, use the following command in the terminal:

Then, open your browser and navigate to http://localhost:3000 to see the app in action.

You can create, edit, and delete items as needed, and the application will update the data in the MongoDB database.

Conclusion

Building a simple CRUD application is a great way to understand the core functionality that drives most web applications. In this tutorial, we created a Node.js application that uses MongoDB to manage items and performs the basic CRUD operations. We also used EJS for the frontend to dynamically display data and handle form submissions.

This is just the beginning; there are many ways to expand this application, such as adding validation, authentication, or incorporating more complex relationships between data. However, mastering the basics of CRUD operations is a key foundation for building more advanced web applications.

With the knowledge from this tutorial, you now have a solid understanding of how to build a simple CRUD application from scratch. Keep experimenting and building upon this foundation!

Other Products

How to Build a Brand for Your Homemade Soap Business
How to Build a Brand for Your Homemade Soap Business
Read More
How to Clean Your House Using the "One Hour" Method
How to Clean Your House Using the "One Hour" Method
Read More
How to Make a Checklist for Optimizing Product Photography for E-commerce
How to Make a Checklist for Optimizing Product Photography for E-commerce
Read More
How To Practice Journaling with Stoic Prompts
How To Practice Journaling with Stoic Prompts
Read More
How to Save Money on Landscaping and Outdoor Projects
How to Save Money on Landscaping and Outdoor Projects
Read More
How to Use Spreadsheets for Budgeting Success
How to Use Spreadsheets for Budgeting Success
Read More