DEV Community

Cover image for Beginner's Tutorial for CRUD Operations in NodeJS and MongoDB
Daniel Musembi
Daniel Musembi

Posted on

Beginner's Tutorial for CRUD Operations in NodeJS and MongoDB

Introduction

CRUD operations stand for Create, Read, Update, and Delete. This procedure allows you to work with data from the MongoDB database.

With these four operations, you can create, read, update, and delete data in MongoDB.

What is MongoDB

MongoDB is a powerful and flexible solution for handling modern data needs. As a leading NoSQL database, MongoDB offers a dynamic schema design, enabling developers to store and manage data in a way that aligns seamlessly with contemporary application requirements.

What is Nodejs

Node.js is a runtime environment that allows you to run JavaScript on the server side, rather than just in the browser. It's built on Chrome's V8 JavaScript engine, making it fast and efficient. With Node.js, you can build scalable network applications easily, using a single programming language for both client and server-side code. It's especially good for handling many simultaneous connections and real-time applications like chat servers or online games.

Prequisite

  • Install Node.js: Download and install Node.js from the official website if you haven't already.

  • Install MongoDB: Install MongoDB on your machine. Follow the instructions on the official MongoDB website.

Step 1: Initialize a new project

Open your preferred code editor (VS code) and cd into the directory where you want to create the project, then enter the command below to create a new project.

npm init
Enter fullscreen mode Exit fullscreen mode

Next, use the command below to install the necessary packages.

 npm install express mongodb
Enter fullscreen mode Exit fullscreen mode

To ensure that everything is working properly, add '"serve": "node index.js"' beneath the script in the package.JSON for starting the program.

Image description

Create and test express.js server

In the root directory create an index.js file and enter the following code in it.

const express = require('express')
const app = express()

app.listen(3000, () =>{
    console.log('Server is running on port 3000')
});

app.get('/', (req, res) =>{
    res.send("Hello Node API")
})
Enter fullscreen mode Exit fullscreen mode

In this code, we create a basic Node.js server using the Express framework, which listens on port 3000. When you visit the root URL ("/"), it responds with the message "Hello Node API".

Now run the application with the command 'npm run serve' to observe the results, as shown below.

Image description

To test if the server is working enterlocalhost:3000 on the browser and see the results as shown below.

Image description

Creating MongoDB connection

Visit mongodb and sign in into your account or create one if not yet.

Create a new project. Give it a name and click "Create Project."

Image description

Click the Create button, and then select the free m0 template. Scroll down, give your cluster a name, and click Create deployment.

Image description

Image description

On the following screen, enter a username and password for your cluster; make sure to copy or remember the password. Click Create Database user.

After that click on the Choose a connection method button and select Connect
Image description via drivers, copy the connection string.

To access mongodb we need a dependency called mongoose, so make sure to install it npm i mongoose and add it at the top in the index.js file const mongoose = require('mongoose');.

Create a db.js file in the root directory and paste the following code, replacing with the password you created.

const mongoose = require('mongoose');

mongoose.connect("mongodb+srv://admindan:admin1234@crudbackend.5goqnqm.mongodb.net/?retryWrites=true&w=majority&appName=crudbackend")
.then(() => {
    console.log('Connected to the database');
})
.catch((error) => {
    console.log('Connection failed', error);
});

module.exports = mongoose;
Enter fullscreen mode Exit fullscreen mode

Import const mongoose = require('./db'); at the top of the index.js file

To test if the database is connecting run the application and you should see results on the terminal as shown below.

Image description

Creating CRUD functions

Now that we've our database connected, we need a model to store our data in the mongodb.

Make a models folder in the root directory, then create a file called "product.model.js" and insert the following code into it.

const mongoose = require("mongoose");

const ProductSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please enter product name"],
    },

    quantity: {
      type: Number,
      required: true,
      default: 0,
    },

    price: {
      type: Number,
      required: true,
      default: 0,
    },

    image: {
      type: String,
      required: false,
    },
  },
  {
    timestamps: true,
  }
);


const Product = mongoose.model("Product", ProductSchema);

module.exports = Product;
Enter fullscreen mode Exit fullscreen mode

Create: defining a function to insert data into mongodb

We're creating a function for storing data in our MongoDB collection. Create a controllers folder in the root directory and a file called 'product.controller.js' within it. Paste the following code in it.

const Product = require("../models/product.model");

const getProducts = async (req, res) => {
  try {
    const products = await Product.find({});
    res.status(200).json(products);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const getProduct = async (req, res) => {
  try {
    const { id } = req.params;
    const product = await Product.findById(id);
    res.status(200).json(product);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const createProduct = async (req, res) => {
  try {
    const product = await Product.create(req.body);
    res.status(200).json(product);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const updateProduct = async (req, res) => {
  try {
    const { id } = req.params;

    const product = await Product.findByIdAndUpdate(id, req.body);

    if (!product) {
      return res.status(404).json({ message: "Product not found" });
    }

    const updatedProduct = await Product.findById(id);
    res.status(200).json(updatedProduct);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const deleteProduct = async (req, res) => {
  try {
    const { id } = req.params;

    const product = await Product.findByIdAndDelete(id);

    if (!product) {
      return res.status(404).json({ message: "Product not found" });
    }

    res.status(200).json({ message: "Product deleted successfully" });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

module.exports = {
  getProducts,
  getProduct,
  createProduct,
  updateProduct,
  deleteProduct,
};
Enter fullscreen mode Exit fullscreen mode

In this code, we define CRUD operations for our Product model It includes:

  • getProducts: Fetches all products.

  • getProduct: Fetches a product by its ID.

  • createProduct: Creates a new product with provided data.

  • updateProduct: Updates a product by its ID.

  • deleteProduct: Deletes a product by its ID.

Each function handles possible errors and returns appropriate HTTP responses.

Define routes

Create a routes folder at the root directory and in it create product.route.js. Insert the below code in it.

const express = require("express");
const Product = require("../models/product.model.js");
const router = express.Router();
const {getProducts, getProduct, createProduct, updateProduct, deleteProduct} = require('../controllers/product.controller.js');


router.get('/', getProducts);
router.get("/:id", getProduct);

router.post("/", createProduct);

// update a product
router.put("/:id", updateProduct);

// delete a product
router.delete("/:id", deleteProduct);




module.exports = router;
Enter fullscreen mode Exit fullscreen mode

In this code, we set up Express routes for CRUD operations for our Product model. it imports the necessary modules, creates an Express router, and defines routes for:

Fetching all products (GET /).
Fetching a single product by ID (GET /:id).
Creating a new product (POST /).
Updating a product by ID (PUT /:id).
Deleting a product by ID (DELETE /:id).

Finally, it exports the router for use in the main application.

Testing your API

Now that we've created our CRUD operations, let's test them. We are going to use insomnia if you don't have it you can download and create an account.

Follow the steps outlined below to test create operation ( POST REQUEST).

  • Open Insomnia: Launch the Insomnia application.

  • Create a New Request: Click on the "+" button to create a new request.

  • Set Request Type: Select "POST" from the dropdown menu next to the request name.

  • Enter URL: Input the URL of your API endpoint ( http://localhost:3000/api/products)

  • Enter Request Body: Click on the "Body" tab, select "JSON," and enter the JSON data you want to send.

  • Send Request: Click the "Send" button to send the request to the server.

  • View Response: Inspect the response from the server in the lower pane of Insomnia.

The api for creating a product on the MongoDB was successful, as indicated by the status 200 ok in the image below, which illustrates how it should operate.

Image description

Thus, you ought to be able to view the item created when you navigate to the database and select Browse Collection.

Image description

Test Read operations

The technique of testing a get request is almost the same as what we discussed above; you make a new request and select GET from the dropdown menu.

Image description

Proceed to try the final two options, which are update and remove (PUT, DELETE) from the dropdown menu.

Conclusion

With this beginner's tutorial, you should now have a solid foundation for performing CRUD operations using NodeJS and MongoDB. For more tech insights, follow me on X and connect on LinkedIn.

Top comments (0)