Page cover

Building a CRUD Application with Node.js and MongoDB

Node.js and MongoDB form a popular technology stack for building modern web applications. This article will guide you through creating a simple CRUD (Create, Read, Update, Delete) application using Node.js and MongoDB.

Prerequisites

Before you start, ensure you have the following installed:

  1. Node.js and npm (Node Package Manager)

  2. MongoDB (either locally or using a cloud service like MongoDB Atlas)

  3. A code editor like Visual Studio Code

Setting Up the Project

Step 1: Initialize the Project

First, create a new directory for your project and initialize a Node.js project:

mkdir node-mongo-crud
cd node-mongo-crud
npm init -y

Step 2: Install Dependencies

Install the necessary dependencies:

npm install express mongoose body-parser
  • express: A minimal and flexible Node.js web application framework.

  • mongoose: An ODM (Object Data Modeling) library for MongoDB and Node.js.

  • body-parser: Middleware to parse incoming request bodies in a middleware before your handlers, available under the req.body property.

Step 3: Set Up the Project Structure

Create the following folder structure:

node-mongo-crud/
├── models/
│   └── user.js
├── routes/
│   └── userRoutes.js
├── app.js
└── package.json

Creating the CRUD Application

Step 4: Configure MongoDB

Create a models/user.js file and define the User schema:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    }
});

const User = mongoose.model('User', userSchema);

module.exports = User;

Step 5: Define Routes

Create a routes/userRoutes.js file and define the CRUD routes:

const express = require('express');
const User = require('../models/user');

const router = express.Router();

// Create a new user
router.post('/users', async (req, res) => {
    try {
        const user = new User(req.body);
        await user.save();
        res.status(201).send(user);
    } catch (error) {
        res.status(400).send(error);
    }
});

// Get all users
router.get('/users', async (req, res) => {
    try {
        const users = await User.find();
        res.status(200).send(users);
    } catch (error) {
        res.status(500).send(error);
    }
});

// Get a single user by ID
router.get('/users/:id', async (req, res) => {
    try {
        const user = await User.findById(req.params.id);
        if (!user) {
            return res.status(404).send();
        }
        res.status(200).send(user);
    } catch (error) {
        res.status(500).send(error);
    }
});

// Update a user
router.put('/users/:id', async (req, res) => {
    try {
        const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
        if (!user) {
            return res.status(404).send();
        }
        res.status(200).send(user);
    } catch (error) {
        res.status(400).send(error);
    }
});

// Delete a user
router.delete('/users/:id', async (req, res) => {
    try {
        const user = await User.findByIdAndDelete(req.params.id);
        if (!user) {
            return res.status(404).send();
        }
        res.status(200).send(user);
    } catch (error) {
        res.status(500).send(error);
    }
});

module.exports = router;

Step 6: Set Up the Express Application

Create an app.js file to set up the Express application:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');

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

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

mongoose.connect('mongodb://localhost:27017/nodecrud', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
    .then(() => {
        console.log('Connected to MongoDB');
        app.listen(port, () => {
            console.log(`Server running on port ${port}`);
        });
    })
    .catch(error => {
        console.error('Connection error', error.message);
    });

Step 7: Run the Application

Make sure your MongoDB server is running. You can start your MongoDB server using:

mongod

Then, run your Node.js application:

node app.js

Your application should now be running on http://localhost:3000.

Testing the CRUD Endpoints

Use a tool like Postman or curl to test the endpoints:

  • Create a new user:

    curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Alice","email":"alice@example.com"}'
  • Get all users:

    curl -X GET http://localhost:3000/users
  • Get a user by ID:

    curl -X GET http://localhost:3000/users/<user_id>
  • Update a user:

    curl -X PUT http://localhost:3000/users/<user_id> -H "Content-Type: application/json" -d '{"name":"Alice Updated","email":"alice.updated@example.com"}'
  • Delete a user:

    curl -X DELETE http://localhost:3000/users/<user_id>

Conclusion

You've now built a complete CRUD application using Node.js and MongoDB. This application serves as a basic template that you can expand and customize to fit more complex requirements. With Node.js and MongoDB, you have the flexibility and scalability to build robust web applications. Happy coding!

Last updated