How to create a simple CRUD application in Node.js

How to Create a Simple CRUD Application in Node.js

Creating a CRUD (Create, Read, Update, Delete) application is one of the fundamental skills for any backend developer. In this article, we will walk you through the process of building a simple CRUD application using Node.js. We’ll cover the essentials, including definitions, use cases, and a step-by-step implementation. By the end, you'll have a fully functional application that you can expand upon.

What is CRUD?

CRUD is an acronym that stands for Create, Read, Update, and Delete. These are the four basic operations that you can perform on data in a database. Understanding CRUD is essential for building applications that interact with a database, as it forms the backbone of data manipulation.

Use Cases for CRUD Applications

CRUD applications are ubiquitous in software development. They can be used for:

  • Content Management Systems (CMS): Managing articles, blogs, and user-generated content.
  • Inventory Systems: Keeping track of products, stock levels, and orders.
  • User Management: Handling user profiles, settings, and permissions.
  • Task Management: Organizing and tracking tasks or projects.

Setting Up the Project

To create our CRUD application, we will use Node.js along with Express.js for routing and MongoDB for our database. Let’s get started!

Prerequisites

Before we begin coding, ensure you have the following installed:

  • Node.js
  • npm (Node Package Manager)
  • MongoDB (or MongoDB Atlas for cloud database)

Step 1: Initialize the Project

Create a new directory for your project and navigate to it:

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

Now initialize a new Node.js project:

npm init -y

Step 2: Install Required Packages

We will need to install Express and Mongoose (an ODM for MongoDB):

npm install express mongoose body-parser

Step 3: Set Up the Server

Create a file named server.js in your project directory. This will be the entry point of our application.

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

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

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

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

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

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

Step 4: Define a Model

Next, we will define a Mongoose model for our data. Create a folder named models and inside it, create a file named Item.js. The model will represent a simple item with a name and description.

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 we will implement the CRUD operations in the server.js file.

Create an Item

Add the following route to create a new item:

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

// Create Item
app.post('/items', async (req, res) => {
    const newItem = new Item(req.body);
    try {
        const savedItem = await newItem.save();
        res.status(201).json(savedItem);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

Read All Items

Add a route to read all items:

// Read All Items
app.get('/items', async (req, res) => {
    try {
        const items = await Item.find();
        res.status(200).json(items);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

Update an Item

Now, let’s add a route to update an item:

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

Delete an Item

Finally, we will add a route to delete an item:

// Delete Item
app.delete('/items/:id', async (req, res) => {
    try {
        await Item.findByIdAndDelete(req.params.id);
        res.status(204).json({ message: 'Item deleted' });
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

Step 6: Testing the Application

You can test your CRUD application using tools like Postman or Insomnia. Here are the endpoints you can use:

  • POST /items to create an item
  • GET /items to retrieve all items
  • PUT /items/:id to update an item
  • DELETE /items/:id to delete an item

Conclusion

Congratulations! You’ve built a simple CRUD application in Node.js. This foundational knowledge is crucial for developing more complex applications. You can further enhance this application by adding user authentication, error handling, or even a front-end interface.

Whether you’re building a personal project or a scalable application, mastering CRUD operations will equip you with the skills to manage data effectively. Keep experimenting and building to deepen your understanding of Node.js and database interactions. 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.