,

Step-by-Step Guide: Performing CRUD Operations with ExpressJS & MongoDB

Posted by






Tutorial #20: CRUD Operations Using ExpressJS & MongoDB

Tutorial #20: CRUD Operations Using ExpressJS & MongoDB

In this tutorial, we will learn how to perform CRUD (Create, Read, Update, Delete) operations using ExpressJS and MongoDB. This will cover the basic operations required to interact with a MongoDB database using an ExpressJS application.

Setup

Before we start, make sure you have Node.js and MongoDB installed on your machine. You can install them by following the official documentation on their respective websites.

Creating a New ExpressJS Project

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

Next, install the necessary dependencies using npm:

    
      $ npm install express mongoose
    
  

Creating a MongoDB Database

Open the terminal and run the MongoDB server using the following command:

    
      $ mongod
    
  

Then, open another terminal window and connect to the MongoDB database using the mongo shell:

    
      $ mongo
    
  

Create a new database and a collection:

    
      > use express_mongodb_crud
      > db.createCollection('users')
    
  

Creating the ExpressJS Application

Create a new file called index.js and add the following code:

    
      const express = require('express');
      const mongoose = require('mongoose');
      
      const app = express();
      const port = 3000;
      
      // Connect to MongoDB
      mongoose.connect('mongodb://localhost:27017/express_mongodb_crud', { useNewUrlParser: true, useUnifiedTopology: true });
      
      // Define a schema
      const userSchema = new mongoose.Schema({
        name: String,
        email: String
      });
      
      const User = mongoose.model('User', userSchema);
      
      app.use(express.json());
      
      // Create a new user
      app.post('/users', async (req, res) => {
        try {
          const user = new User(req.body);
          await user.save();
          res.send(user);
      } catch (error) {
          res.status(500).send(error);
        }
      });
      
      // Read all users
      app.get('/users', async (req, res) => {
        const users = await User.find();
        res.send(users);
      });
      
      // Update a user by ID
      app.patch('/users/:id', async (req, res) => {
        try {
          const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
          res.send(user);
        } catch (error) {
          res.status(500).send(error);
        }
      });
      
      // Delete a user by ID
      app.delete('/users/:id', async (req, res) => {
        try {
          const user = await User.findByIdAndDelete(req.params.id);
          res.send(user);
        } catch (error) {
          res.status(500).send(error);
        }
      });
      
      app.listen(port, () => {
        console.log(`Server is running on port ${port}`);
      });
    
  

Save the file and run the application using the following command:

    
      $ node index.js
    
  

That’s it! You have now created an ExpressJS application that can perform CRUD operations using MongoDB. You can test the endpoints using a tool like Postman or by creating a front-end application that interacts with the API.

Thank you for following along with this tutorial! Happy coding!