Home > Uncategorized > Creating a Node.js Express API with MongoDB

Creating a Node.js Express API with MongoDB

# Creating a Node.js Express API with MongoDB

Node.js and Express are a powerful combination for building APIs. When paired with MongoDB, they form an efficient stack for handling database operations in modern web applications. In this technical guide, we’ll walk through creating a RESTful API using Node.js, Express, and MongoDB. We’ll cover setting up the project, connecting to MongoDB, and implementing CRUD operations.

## Prerequisites

Before we begin, ensure you have the following installed:
– **Node.js** (v14 or later)
– **MongoDB** (local or cloud-based, e.g., MongoDB Atlas)
– **npm** (comes with Node.js)

## Step 1: Setting Up the Project

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

mkdir node-express-api
cd node-express-api
npm init -y

This will create a `package.json` file. Next, install the required dependencies:

npm install express mongoose body-parser cors

– **Express**: A web application framework for Node.js.
– **Mongoose**: A MongoDB object data modeling (ODM) library.
– **Body-parser**: Middleware to parse incoming JSON request bodies.
– **CORS**: Middleware to enable Cross-Origin Resource Sharing.

## Step 2: Creating the Server File

Create a file named `server.js` in the root of your project. This file will contain the Express server setup and routes.

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

const app = express();
const PORT = 5000;

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

// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/mydatabase', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('Connected to MongoDB');
}).catch((error) => {
    console.error('MongoDB connection error:', error);
});

// Sample Route
app.get('/', (req, res) => {
    res.send('API is running...');
});

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

In this code:
– We set up middleware for JSON parsing (`body-parser`) and CORS.
– Connected to a local MongoDB instance (`mongodb://localhost:27017/mydatabase`).
– Created a sample route (`GET /`).

## Step 3: Creating the MongoDB Model

Define a schema for MongoDB collections using Mongoose. Create a folder named `models` and add a file named `User.js`.

const mongoose = require('mongoose');

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

module.exports = mongoose.model('User', UserSchema);

This schema defines a `User` collection with fields `name`, `email`, and `age`. MongoDB will automatically add `_id` and timestamps (createdAt, updatedAt) to each document.

## Step 4: Implementing CRUD Operations

Now, create routes to handle CRUD operations for the `User` model. Create a new file named `routes.js`:

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).json(user);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});

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

// Get a 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).json({ message: 'User not found' });
        }
        res.status(200).json(user);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// 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).json({ message: 'User not found' });
        }
        res.status(200).json(user);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});

// 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).json({ message: 'User not found' });
        }
        res.status(200).json({ message: 'User deleted' });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

module.exports = router;

Add these routes to the `server.js` file:

const userRoutes = require('./routes');
app.use('/api', userRoutes);

Now, all routes are prefixed with `/api`.

## Step 5: Testing the API

You can test the API using tools like **Postman** or **cURL**. Here’s a summary of the endpoints:

– **POST /api/users**: Create a new user.
– **GET /api/users**: Fetch all users.
– **GET /api/users/:id**: Fetch a specific user by ID.
– **PUT /api/users/:id**: Update a user by ID.
– **DELETE /api/users/:id**: Delete a user by ID.

Example payload for creating a user:

{
    "name": "John Doe",
    "email": "john.doe@example.com",
    "age": 30
}

## Conclusion

You’ve successfully created a Node.js Express API with MongoDB integration! This setup is scalable and can be extended with more features such as authentication, validation, and deployment. With MongoDB as your database, you can efficiently handle large datasets and complex queries.

Node.js API, Express Mongo