We are going to discuss CRUD operations namely create, read, update, and delete on a database resource in NodeJS application. Node.js is an open-sourced, free, cross-platform JavaScript run-time environment for server-side scripting. 

Application Environment ?

We are using the express framework in NodeJS. Along with we are using sequelize to interact with MYSQL database. Sequelize is a powerful ORM module that features solid transaction support, relations, eager and lazy loading, read replication, and many more.

Packages that are needed includes:

  • sequelize
    • As discussed earlier, it is a powerful ORM module that features solid transaction support, relations, eager and lazy loading, read replication, and many more.
  • sequelize-cli
    • Provide a command-line tool for performing sequelize operations and generating files.
  • mysql2
    • A module that provides MySQL capability.
  • express
    • NodeJS powerful and super easy framework
  • body-parser
    • A module to extract data from the request body.
  • cors (optional)
    • A module to provide Cross-origin resource sharing capability. i.e A request from other domains can be allowed to serve.
npm i --save sequelize express mysql2 body-parser cors 

Directory Structure

How it works?

It basically creates models for each table and out code interact with these models, for more visit here -> https://adeshkumarsingh.com/blog/2020/05/27/working-with-sequelize/

So Your application flow on NodeJS server would be

[main_server_file] <=> [routes] <=> [controller] <=> [model]

From the above link, you will get to know how models work. Now let’s focus on the controller and routes and main_server_file here.

EmailRoute.js file

module.exports = (app) => {
    const EmailController = require('../controllers/EmailController');
    var router = require("express").Router();

    router.get("/", EmailController.userEmailViewAll);
    router.get("/:id", EmailController.userEmailViewById);
    router.post("/", EmailController.userEmailSave);
    router.put('/:id', userEmailSave.userEmailUpdate);
    router.delete("/:id", EmailController.userEmailDelete);

    app.use('/email',  router);
}

Above route code will interract with controller named as EmailController to fetch all the records, fetch on record by id, create the new record, update the existing record and delete the record by id.

EmailController.js file

// fetching all the records from the database

exports.userEmailViewAll = (req, res) => {
    EmailModel.findAll({}).then((databaseRecords) => {
        if(databaseRecords == null) {
            res.status(204).send();
        } else {
            res.status(200).send(databaseRecords);
        }
    }).catch((error) => {
        res.status(500).send();
    })
};
//fetching the single record by record-id

exports.userEmailViewById= (req, res) => {
    let id = req.params.id;
    EmailModel.findAll({
           where: {
               id: id
            }
    }).then((databaseRecords) => {
        if(databaseRecords == null) {
            res.status(204).send();
        } else {
            res.status(200).send(databaseRecords);
        }
    }).catch((error) => {
        res.status(500).send();
    })
};
//saving single instance of record in database

exports.userEmailSave= (req, res) => {
    let user_email = req.body.user_email;
    let email_type = req.body.email_type;
    EmailModel.findOrCreate({
           where: {
               email: user_email,
               type: email_type
            }
    }).then((databaseRecords) => {
        if(databaseRecords == null) {
            res.status(204).send();
        } else {
            res.status(200).send(databaseRecords);
        }
    }).catch((error) => {
        res.status(500).send();
    })
};
// updating the record by id
// here we are passing req.body which means if req.body contains one record then it will update one records, and if multiple so multiple fields will be updated

exports.userEmailUpdate = (req, res) => {
    let user_email = req.body.user_email;
    let email_type = req.body.email_type;
    EmailModel.update({
           req.body,
           where: {
               email: user_email,
               type: email_type
            }
    }).then((databaseRecords) => {
        if(databaseRecords == null) {
            res.status(204).send();
        } else {
            res.status(200).send(databaseRecords);
        }
    }).catch((error) => {
        res.status(500).send();
    })
};
// delete the record by id

exports.userEmailDelete= (req, res) => {
    let record_id = req.params.id;
    EmailModel.destroy({
           where: {
               id: record_id
            }
    }).then((databaseRecords) => {
        if(databaseRecords == null) {
            res.status(204).send();
        } else {
            res.status(200).send(databaseRecords);
        }
    }).catch((error) => {
        res.status(500).send();
    })
};

Now finally add the above router in your main server file as described below.

start.js file

var express = require('express');
var app = express();
var bodyParser = require('body-parser')
const cors = require('cors');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

require("./application/routes/EmailRoute")(app);

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.