Express.js tutorial with examples using CRUD operations

 In this tutorial, we will walk through how to set up a simple Express.js server with CRUD (Create, Read, Update, Delete) operations. Express.js is a minimalist web framework for Node.js that makes it easy to build robust web applications and APIs.

We will build a basic Todo API with Express.js and use MongoDB as the database to store our todos. MongoDB is a NoSQL database that stores data in a flexible, JSON-like format.

Steps:

  1. Setting up Express.js
  2. Creating CRUD operations (Create, Read, Update, Delete)
  3. Connecting to MongoDB
  4. Testing the API with Postman

1. Setting up the Project

1.1. Install Node.js and Express

First, ensure that Node.js is installed on your machine. If not, download and install it from nodejs.org.

Now, create a new project directory and initialize the project:

mkdir express-crud cd express-crud npm init -y

This will create a package.json file in your project directory.

Next, install Express.js and Mongoose (the MongoDB ODM for Node.js):

npm install express mongoose body-parser
  • express: Web framework for Node.js.
  • mongoose: MongoDB ODM to manage data models and interact with MongoDB.
  • body-parser: Middleware to parse incoming request bodies, especially for POST and PUT requests.

1.2. Project Structure

Create the following folder structure for your project:

express-crud/ ├── models/ │ └── todo.model.js ├── routes/ │ └── todo.routes.js ├── app.js └── config/ └── db.js

2. Connecting to MongoDB

2.1. MongoDB Setup

To use MongoDB, you need to have MongoDB installed locally or use a cloud service like MongoDB Atlas.

  1. Install MongoDB locally or sign up for MongoDB Atlas and create a database.

  2. Create a database called todoapp or use the default database.

2.2. Database Configuration (db.js)

Create a config/db.js file to handle MongoDB connection using Mongoose:

// config/db.js const mongoose = require('mongoose'); const dbURI = 'mongodb://localhost:27017/todoapp'; // MongoDB URI (replace with your connection string if using Atlas) mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('MongoDB connected'); }) .catch((err) => { console.error('MongoDB connection error:', err); }); module.exports = mongoose;

This code connects to a MongoDB instance running locally on port 27017 and uses the database todoapp.


3. Creating a Todo Model

3.1. Define Todo Schema (todo.model.js)

In the models folder, create a file todo.model.js. This will define the structure of our Todo data:

// models/todo.model.js const mongoose = require('mongoose'); const todoSchema = new mongoose.Schema({ title: { type: String, required: true }, completed: { type: Boolean, default: false }, }, { timestamps: true }); const Todo = mongoose.model('Todo', todoSchema); module.exports = Todo;

This schema defines:

  • title: A string that is required.
  • completed: A boolean field with a default value of false.
  • timestamps: Automatically adds createdAt and updatedAt fields to the document.

4. Setting Up CRUD Routes

4.1. Define Routes for CRUD Operations (todo.routes.js)

Create a routes folder and inside it, create a file todo.routes.js to handle the routes for Create, Read, Update, and Delete operations:

// routes/todo.routes.js const express = require('express'); const Todo = require('../models/todo.model'); const router = express.Router(); // Create - Add a new Todo router.post('/todos', async (req, res) => { const { title, completed } = req.body; try { const newTodo = new Todo({ title, completed, }); const savedTodo = await newTodo.save(); res.status(201).json(savedTodo); } catch (err) { res.status(500).json({ message: 'Error creating Todo', error: err }); } }); // Read - Get all Todos router.get('/todos', async (req, res) => { try { const todos = await Todo.find(); res.status(200).json(todos); } catch (err) { res.status(500).json({ message: 'Error fetching Todos', error: err }); } }); // Read - Get a Todo by ID router.get('/todos/:id', async (req, res) => { const { id } = req.params; try { const todo = await Todo.findById(id); if (!todo) return res.status(404).json({ message: 'Todo not found' }); res.status(200).json(todo); } catch (err) { res.status(500).json({ message: 'Error fetching Todo', error: err }); } }); // Update - Update a Todo by ID router.put('/todos/:id', async (req, res) => { const { id } = req.params; const { title, completed } = req.body; try { const updatedTodo = await Todo.findByIdAndUpdate(id, { title, completed }, { new: true }); if (!updatedTodo) return res.status(404).json({ message: 'Todo not found' }); res.status(200).json(updatedTodo); } catch (err) { res.status(500).json({ message: 'Error updating Todo', error: err }); } }); // Delete - Delete a Todo by ID router.delete('/todos/:id', async (req, res) => { const { id } = req.params; try { const deletedTodo = await Todo.findByIdAndDelete(id); if (!deletedTodo) return res.status(404).json({ message: 'Todo not found' }); res.status(200).json({ message: 'Todo deleted' }); } catch (err) { res.status(500).json({ message: 'Error deleting Todo', error: err }); } }); module.exports = router;

4.2. Use the Routes in the Main App (app.js)

In the app.js file, import the necessary modules, set up the server, and use the todo.routes.js file for the routes.

// app.js const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('./config/db'); // MongoDB connection const todoRoutes = require('./routes/todo.routes'); // Todo routes const app = express(); // Middleware app.use(bodyParser.json()); // Parse JSON request bodies // Use Todo routes app.use('/api', todoRoutes); // Start server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });

5. Testing the API

5.1. Start the Server

Start the server by running the following command:

node app.js

The server will be running at http://localhost:3000.

5.2. Test with Postman or CURL

You can use Postman or CURL to test the CRUD API.

  1. Create a Todo (POST request)

    URL: http://localhost:3000/api/todos

    Body (JSON):

    { "title": "Learn Express.js", "completed": false }
  2. Get All Todos (GET request)

    URL: http://localhost:3000/api/todos

  3. Get Todo by ID (GET request)

    URL: http://localhost:3000/api/todos/{id}

  4. Update a Todo (PUT request)

    URL: http://localhost:3000/api/todos/{id}

    Body (JSON):

    { "title": "Learn Express.js and MongoDB", "completed": true }
  5. Delete a Todo (DELETE request)

    URL: http://localhost:3000/api/todos/{id}


6. Conclusion

In this tutorial, we've created a simple CRUD API with Express.js and MongoDB using Mongoose. Here's a summary of what we've done:

  • Set up Express.js and MongoDB.
  • Created a Todo model using Mongoose.
  • Built routes to handle CRUD operations for the Todo app.
  • Tested the API using Postman or CURL.

This is a basic API that can be extended with more advanced features like authentication, validation, and error handling as you build more complex applications.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics