how-to-create-a-basic-crud-application-in-nodejs.html

How to Create a Basic CRUD Application in Node.js

Node.js is a powerful platform for building scalable network applications. Among its many use cases, creating a CRUD (Create, Read, Update, Delete) application is one of the most fundamental. In this article, we will walk through the process of building a basic CRUD application using Node.js, Express, and MongoDB.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete. These four operations represent the basic functions of persistent storage in a database. A CRUD application allows users to perform these operations on data, making it essential for web development.

Use Cases for CRUD Applications

  • Content Management Systems (CMS): Allow users to create, edit, and delete content.
  • Task Management Tools: Enable users to manage tasks with CRUD functionalities.
  • E-commerce Platforms: Support product management through CRUD operations.
  • User Management Systems: Allow administrators to manage user accounts.

Setting Up Your Environment

Before diving into the code, let's set up our development environment. Make sure you have the following installed:

  • Node.js: Download from nodejs.org.
  • MongoDB: Install from mongodb.com.
  • Postman: For testing your API endpoints.

Initializing Your Project

  1. Create a new directory for your project:

bash mkdir node-crud-app cd node-crud-app

  1. Initialize a new Node.js project:

bash npm init -y

  1. Install necessary packages:

bash npm install express mongoose body-parser cors

Project Structure

Your project structure should look like this:

node-crud-app/

├── node_modules/
├── package.json
├── server.js
└── models/
    └── Item.js

Writing the Code

1. Setting Up the Server

Create a file named server.js and add the following code to set up your 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());

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/crud-app', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => console.log('MongoDB connected'))
  .catch(err => console.log(err));

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

2. Defining the Model

Next, create a file called Item.js in the models directory. This file will define the schema for our items:

const mongoose = require('mongoose');

const ItemSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    quantity: {
        type: Number,
        required: true
    },
}, { timestamps: true });

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

3. Implementing CRUD Operations

Now, let's implement the CRUD operations in the server.js file. We will create routes for each operation.

Create an 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(500).json(err);
    }
});

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(err);
    }
});

Update an 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(500).json(err);
    }
});

Delete an Item

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

Full Code for server.js

Here’s how your complete server.js file should look:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const Item = require('./models/Item');

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

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

mongoose.connect('mongodb://localhost:27017/crud-app', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => console.log('MongoDB connected'))
  .catch(err => console.log(err));

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(500).json(err);
    }
});

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

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(500).json(err);
    }
});

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

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

Testing Your CRUD Application

Now that we have our CRUD application set up, it’s time to test it using Postman.

  • Create: Send a POST request to http://localhost:5000/items with a JSON body containing name and quantity.
  • Read: Send a GET request to http://localhost:5000/items.
  • Update: Send a PUT request to http://localhost:5000/items/:id with the updated data.
  • Delete: Send a DELETE request to http://localhost:5000/items/:id.

Conclusion

Congratulations! You've successfully created a basic CRUD application using Node.js, Express, and MongoDB. This foundational knowledge can serve as a springboard for more complex applications and integrations. As you continue to learn, consider implementing error handling, user authentication, and front-end frameworks to enhance your application further. 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.