CRUD API using the Node JS & MongoDB

Share

This article will show how to create a REST API for basic CRUD using NodeJS and MongoDB. We will create REST APIs for creating, updating, reading, and deleting a blog post.

Before starting with Create, Read, Update and Delete data in the express application, you should go through these articles.

Node JS Articles: https://codewithsudeep.com/category/javascript/nodejs/

Let’s get started and create a CRUD app in node/express.

Creating a node application with express js

You can start by creating the express application on your own. Also, clone the repository provided in the below link for the new express application. it comes with mongoose installed.

Boilerplate Template: https://github.com/SudeepMi/node-crud

Boilerplate folder structure:

This boilerplate contains a source code to run node applications with a database connection. Also, it includes an empty file for the corresponding controller, model, and route.

Creating Models

For entity blogs, we have attributes like: title, category, author, comments, etc. To create a model place the following code in your models/Blog.js file.

const { Schema, model } = require('mongoose')
  
const blogSchema = new Schema({
    title : {
        type : String,
        required : true,
    },
    content:{
        type: String,
        required: true
    },
    author:{
        type: String,
        required: true
    },
    category:{
            type: String,
            required:true
        },
    
}, {timestamps : true })


const Blog = model('blogs', blogSchema)
module.exports = Blog

In the model file, we assign attributes along with corresponding data types, constraints, and validations.

Creating Controllers

controllers/blogController.js , we write all methods which are responsible to be executed behind the scene.

// blogController.js

const Blog = require('../models/Blog')


exports.createBlog = async (req, res) => {
  try {   
    const blog = await Blog.create(req.body);
    res.status(201).json({ status: "success", data: { blog } });
  } catch (error) {
    res.send(error.errors) 
  }
};


exports.getAllBlogs = async (req, res, next) => {
  const allBlogs = await Blog.find({});
  res.status(200).json({ data: allBlogs });
};

exports.getSingleBlog = async (req, res, next) => {
 try {  
   const blog = await Blog.findById(req.params.id);
   if (!blog) {
     return res.status(400).send(new Error('No blog found with that id'));
   }
   res.status(200).json({ status: "success", data:  blog  });
 } catch (error) {
    res.send(error.errors) 
 }

};


exports.updateBlog = async (req, res, next) => {
  try {
    const blog = await Blog.findByIdAndUpdate(req.params.id, req.body, {
      runValidators: false,
      new: true,
    });
  
    if (!blog) {
      return res.status(400).json(new Error('No blog found with that id'));
    }
    res.status(200).json({ status: "success", data: blog });
  } catch (error) {
    res.send(error.errors) 
  }
};


exports.deleteBoardMember = async (req, res) => {
  const blog = await Blog.deleteOne({ id: req.body.id });
  if (blog) {
    res.status(200).json({ status: "success" });
  }
};

Here, I have used async programming to handle each request. Also, error handling is performed using a try-catch block.

Creating API Routes

in routes/blogRoute.js we construct API URLs along with request handler functions i.e. controllers.

// blogRoute.js

const { Router } = require('express')
const router = Router()
const Controller = require('../controllers/blogController');


// get all blogs
router.get('/allblogs',Controller.getAllBlogs)
// get single blog by id
router.get('/blogs/:id', Controller.getSingleBlog)
// create new blog
router.post('/addblog', Controller.createBlog)
// update blog
router.put('/updateblog/:id', Controller.updateBlog)
// delete a blog
router.delete('/deleteblog/:id', Controller.deleteBoardMember)


module.exports = router

After creating the model, controller, and route it is time to configure the index file.

To do so, we do a few changes in index.js

// index.js

const express = require('express')
const mongo = require('mongoose')
const morgan = require("morgan");
const app = express();
// route
const crudRoute = require('./routes/blogRoute')

// middlewares to parse data
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ limit: "10kb" }));
app.use(morgan("dev"))
// routes
app.use("/api", crudRoute);

mongo.connect("mongodb://localhost:27017/crud",).then(()=>console.log("+ MongoDB connected"))
app.listen(3000,()=>console.log("+ App Running \n+ Port: 3000"))

# In line 3, we have imported a package called morgan, used for logging in to a node application.

Testing API

Creating new blogs

Create API
The API call to create a blog

All blogs API

The API call to fetch all blogs

Get a single blog by id API

The API call to get a blog by id

Updating a blog

The API call to update a blog

Delete blog API

Deleting a blog

For testing, I’m using the ThunderClient extension in VS Code.

Other MERN articles: MERN Stack

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: