How to build a simple CRUD application with Node.js

How to Build a Simple CRUD Application with Node.js

Creating a CRUD (Create, Read, Update, Delete) application is one of the fundamental tasks for web developers. It's an excellent way to learn the basics of web development and understand how to interact with a database. In this article, we’ll walk you through building a simple CRUD application using Node.js, Express, and MongoDB.

What is a CRUD Application?

A CRUD application allows users to create, read, update, and delete data. These operations are fundamental for almost any web application that manages data, such as blogs, e-commerce sites, or even social media platforms.

Use Cases for CRUD Applications

  • Blog Platforms: Users can create posts, read existing ones, update them, or delete them.
  • E-commerce Sites: Products can be added, viewed, modified, or removed.
  • Task Management Tools: Users can add tasks, view their progress, update task details, or delete completed tasks.

Getting Started

Before diving into the coding part, ensure you have the following tools installed:

  • Node.js: A JavaScript runtime built on Chrome's V8 engine.
  • MongoDB: A NoSQL database to store your application data.
  • Postman: A tool for testing your APIs.
  • NPM: Node package manager for installing packages.

Step 1: Initialize Your Project

Open your terminal, create a new directory for your project, and navigate into it:

mkdir simple-crud-app
cd simple-crud-app

Next, initialize a new Node.js project:

npm init -y

Step 2: Install Required Packages

To build our application, we need to install several packages:

npm install express mongoose body-parser cors
  • express: A web application framework for Node.js.
  • mongoose: An ODM (Object Data Modeling) library for MongoDB.
  • body-parser: Middleware to parse incoming request bodies.
  • cors: Middleware to enable CORS (Cross-Origin Resource Sharing).

Step 3: Set Up the Server

Create a new file named server.js and set up a basic Express server:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(cors());
app.use(bodyParser.json());

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

// Check MongoDB connection
mongoose.connection.on('connected', () => {
    console.log('Connected to MongoDB');
});

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

Step 4: Define a Data Model

In the same directory, create a folder named models and a file named Item.js inside it. Define the schema for your data:

const mongoose = require('mongoose');

const itemSchema = new mongoose.Schema({
    name: { type: String, required: true },
    description: { type: String, required: true },
});

module.exports = mongoose.model('Item', itemSchema);

Step 5: Implement CRUD Operations

Now, let’s create the routes for our CRUD operations. Add the following code to your server.js file:

const Item = require('./models/Item');

// Create a new item
app.post('/items', async (req, res) => {
    const newItem = new Item(req.body);
    try {
        await newItem.save();
        res.status(201).send(newItem);
    } catch (error) {
        res.status(400).send(error);
    }
});

// Read all items
app.get('/items', async (req, res) => {
    try {
        const items = await Item.find();
        res.status(200).send(items);
    } catch (error) {
        res.status(500).send(error);
    }
});

// Update an item
app.put('/items/:id', async (req, res) => {
    try {
        const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
        res.status(200).send(item);
    } catch (error) {
        res.status(400).send(error);
    }
});

// Delete an item
app.delete('/items/:id', async (req, res) => {
    try {
        await Item.findByIdAndDelete(req.params.id);
        res.status(204).send();
    } catch (error) {
        res.status(500).send(error);
    }
});

Step 6: Testing Your API

Now that your CRUD operations are set up, it's time to test them. Open Postman and follow these steps:

  1. Create an Item:

    • Method: POST
    • URL: http://localhost:5000/items
    • Body: json { "name": "Sample Item", "description": "This is a sample item." }
  2. Read Items:

    • Method: GET
    • URL: http://localhost:5000/items
  3. Update an Item:

    • Method: PUT
    • URL: http://localhost:5000/items/{id}
    • Body: json { "name": "Updated Item", "description": "This is an updated item." }
  4. Delete an Item:

    • Method: DELETE
    • URL: http://localhost:5000/items/{id}

Troubleshooting Common Issues

  • MongoDB Connection Errors: Ensure MongoDB is running on your machine. You can start it using mongod.
  • CORS Issues: If your frontend is on a different port, ensure CORS is properly configured.
  • JSON Parsing Errors: Make sure you are sending the correct content type in your requests.

Conclusion

Congratulations! You have successfully built a simple CRUD application using Node.js, Express, and MongoDB. This application serves as a foundational template that you can expand upon. You can enhance it by adding user authentication, a frontend interface, or deploying it to a cloud service.

By mastering CRUD operations, you're well on your way to becoming proficient in web development. Keep experimenting, and happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.