CRUD Operations using Node JS.

A complete beginner to advance guide.

CRUD Operations using Node JS.

The CRUD

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that are necessary for any database application. In such apps, users must be able to create data, have access to the data in the UI by reading the data, update or edit the data, and delete the data.

CRUD OPERATIONOperation
CreatePerforms INSERT operation to database
ReadRead/ Fetch the data specified
UpdateModifies the data in the database
DeleteDelete the data occurrences from database
💡
Instead of using ad-hoc data-query techniques, many programmers prefer to use CRUD because of its performance..

CRUD operations design using Node JS.

Node JS provides excellent support of promise-based asynchronous JavaScript which can be accessed using Async-await functions

1. First create a JavaScript file name crud-repository.js either by command line or through GUI. (Naming of file doesn't matter)

2. Now Create a class name CrudRepository and write a constructor function for model.

class CrudRepository {
    constructor(model) {
        this.model = model;
    }
}
💡
The benefit of creating a class and wrapping all the CRUD functions is that they can be accessed very easily from anywhere in the repository and will reduce redundancy.

Create

Create operation creates or insert data into database. For example adding data of freshers in collage.

For create operation, we will create async create function in CrudRepository class where we will take data as input and will add data on model which is representing database and will return response when asynchronous operation completes.

async create(data) {
        const response = await this.model.create(data);
        return response;
    }

Read

Read operation used to fetch or get data from the database.

For read operation, we will create async get function in CrudRepository class where we query for data either by any condition or whole. Here we will take data as input and will find it in database through its id. If data is available, it will return the response else will return error with status-code NOT_FOUND.

async get(data) {
        const response = await this.model.findByPk(data);
        if(!response) {
            throw new AppError('Not able to find the resource', StatusCodes.NOT_FOUND);
        }
        return response;
    }

-> For fetching all the data at once, we can design a separate function as getAll() .

async getAll() {
        const response = await this.model.findAll();
        return response;
    }
💡
For better ERROR handling , we can additionally use http-status-codes package which can be downloaded by npm install http-status-codes --save and creating a additional AppError superclass which can handle error and give error message.

Update

Update operation changes or alter the data which is prestored in database.

For update operation, we will create async update function which will take two inputs, data location and updated data. It will update previous data with new given data at mentioned location. Here we are using Id for accessing the location.

async update(id, data) { // data -> {col: value, ....}
        const response = await this.model.update(data, {
            where: {
                id: id
            }
        })
        return response;
    }

Delete

Delete operation deletes the data from the database.

For delete operation, we will create async destroy function which takes data as input which is to be deleted and delete it from database. If data provided is not present in database, it will throw status-code error NOT_FOUND.

 async destroy(data) {
        const response = await this.model.destroy({
            where: {
                id: data
            }
        });
        if(!response) {
            throw new AppError('Not able to find the resource', StatusCodes.NOT_FOUND);
        }
        return response;
    }

Overall our CrudRepository class will be:

class CrudRepository {
    constructor(model) {
        this.model = model;
    }

    async create(data) {
        const response = await this.model.create(data);
        return response;
    }

    async destroy(data) {
        const response = await this.model.destroy({
            where: {
                id: data
            }
        });
        if(!response) {
            throw new AppError('Not able to find the resource', StatusCodes.NOT_FOUND);
        }
        return response;
    }

    async get(data) {
        const response = await this.model.findByPk(data);
        if(!response) {
            throw new AppError('Not able to find the resource', StatusCodes.NOT_FOUND);
        }
        return response;
    }

    async getAll() {
        const response = await this.model.findAll();
        return response;
    }

    async update(id, data) { // data -> {col: value, ....}
        const response = await this.model.update(data, {
            where: {
                id: id
            }
        })
        return response;
    }
}

Now we can export our class by

module.exports = CrudRepository;

As Node JS uses global model for filesharing, we can access our CrudRepository class from anywhere in the project and use crud operations.

Did you find this article valuable?

Support Abhishek Kumar by becoming a sponsor. Any amount is appreciated!