,

Beginner’s Tutorial: Creating a CRUD REST API with Node.js & Express using the MVC Model-View-Controller Approach

Posted by






MVC Model-View-Controller Example | CRUD REST API | Node.js & Express tutorials for Beginners

MVC Model-View-Controller Example | CRUD REST API | Node.js & Express tutorials for Beginners

In the world of web development, the Model-View-Controller (MVC) design pattern is widely used to separate the concerns of an application into three distinct components: the Model, the View, and the Controller. This separation enables developers to create more modular, maintainable, and scalable applications.

The Model

The Model component represents the data and business logic of the application. It interacts with the database, performs CRUD (Create, Read, Update, Delete) operations, and contains the application’s business rules. In our example, we will be creating a CRUD REST API using Node.js and Express.

The View

The View component is responsible for presenting the data to the users. It defines the user interface of the application and handles the interaction with the users. In our tutorial, we will be focusing on creating a REST API, so we won’t be dealing with the View component directly. However, keep in mind that in a real-world application, the View can be implemented using HTML, CSS, and JavaScript.

The Controller

The Controller component acts as the intermediary between the Model and the View. It receives user requests, communicates with the Model to perform the necessary operations, and then renders the appropriate View. It handles the logic of the application and ensures the proper flow of data. In our example, we will be using Node.js and Express to create the REST API routes, which will act as our controllers.

CRUD REST API | Node.js & Express tutorials for Beginners

In this tutorial, we will guide you through the process of creating a basic CRUD REST API using Node.js and Express. We will cover the installation and setup of the necessary tools, the definition of routes and controllers, as well as the implementation of CRUD operations.

By the end of this tutorial, you will have a clear understanding of how to create a simple REST API using the MVC design pattern with Node.js and Express. This knowledge will serve as a strong foundation for building more complex and sophisticated applications in the future.

So, let’s get started with our Node.js and Express tutorial for beginners!


0 0 votes
Article Rating
21 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Dave Gray
8 months ago

MVC (Model-View-Controller) is a popular design pattern for organizing your code. In this tutorial, we organize our Express REST API with MVC. In addition, we complete the CRUD operations for our simple JSON data. If you are just starting out with Node.js & Express, you may want to start at the beginning of this Node.js for Beginners playlist found here: https://www.youtube.com/playlist?list=PL0Zuz27SZ-6PFkIxaJ6Xx_X46avTM1aYw

abdourahman
8 months ago

Thank you so much Dave :). This course has really made my transition into backend easy and interesting 🤝

Cihat KOÇAK
8 months ago

cool

s1zee
8 months ago

Hi, I'm wondering whether I should be using immutability for my functions or not(I've done mine without and tested it out and it seems to be working fine), additionally using immutability consumes more data storage from what I know, and for a larger amount of data that could come into play, afterall im updating the existing database always and not creating a new one so it shouldnt be required but maybe its better viewed or actually is better in some other way or maybe I'm supposed to use it interchangebly depending on each case? Thank you for your great videos

Павел М
8 months ago

Спасибо!!! Отличный канал, прекрасный педагог! Успехов!

Maciej Krasuski
8 months ago

One thing appears to me looking your great video. Having separated 'routes' and 'controllers' layers you should avoid use of http related APIs inside the controller. It should not be coupled to any platform and contain only business logic. Controllers should be easily portable to desktop GUI app and should have nothing to web/http staff. All data passing from web layer and http interaction should be handled by 'routes', and your routes are pretty "dumb" passing all the logic (even web handling one) to controller.

Deepika Arava
8 months ago

Hi Dav, Grate tutorial, Thank you for that. I have a question we have different libraries for API development expressJS, NestJS many more can you suggest me which is best for a realtime steaming application which should read data from a data bricks server continuously

Ahmet Kaya
8 months ago

For sorting the array in ascending order with respect to employees' id in the updateEmployee() function, it would be better the usage below. Just as a recommendation.

data.setEmployees(unsortedArray.sort((a, b) => a.id – b.id))

Jamshid Tashkent
8 months ago

I liked very much
Keep up

rockusbacchus
8 months ago

Thanks!

Brandon Joao Castillo
8 months ago

my employeesController:

“`
const path = require("path");
const fsPromises = require("fs").promises;

const data = {};
data.employees = require("../model/employees.json");

const updateFileEmployees = async (dataFile) => {
const pathFile = path.join(__dirname, "../model", "employees.json");
const employeesData = JSON.stringify(dataFile, "", 2);

// update file employees
await fsPromises.writeFile(pathFile, employeesData, "utf-8");
};

const getAllEmployees = (request, response) => {
console.log(data.employees);
response.json(data.employees);
};

const postNewEmployee = async (request, response) => {
const { firstname, lastname } = request.body;

// create a new employee
const id = data.employees.at(-1).id + 1;
const newEmployee = { id, firstname, lastname };

// update array employees
data.employees.push(newEmployee);

// update file employee
await updateFileEmployees(data.employees);

// send Response
response.json(newEmployee);
};

const updateEmployee = async (request, response) => {
// received updated employee
const employee = request.body;
console.log({ employee });

// update array employees
const index = data.employees.findIndex(({ id }) => id === employee.id);
data.employees[index] = employee;

// update file employees
await updateFileEmployees(data.employees);

// send Response
response.json(employee);
};

const deleteEmployee = async (request, response) => {
const { id } = request.body;

// find Element
const index = data.employees.findIndex((employee) => employee.id === id);

// delete the element of the array;
const employeeDeleted = data.employees.splice(index, 1);

// update file employees
await updateFileEmployees(data.employees);

response.json(employeeDeleted);
};

const getEmployee = (request, response) => {
const { id } = request.params;

// find Element
const index = data.employees.findIndex((employee) => employee.id === +id);

// get the element of the array;
const [employee] = data.employees.slice(index, index + 1);
response.json(employee);
};

module.exports = {
getAllEmployees,
postNewEmployee,
updateEmployee,
deleteEmployee,
getEmployee,
};

“`

Jin Lu
8 months ago

Can we just use sort((a, b) => a.id – b.id) instead of sort((a, b) => a.id > b.id ? 1: a.id < b.id ? -1 : 0) in updateEmployee when sorting the array?

Louis Shine
8 months ago

Thank you very much.

In this lesson (after copy-pasting your source code) –

Thunder Client doesn't respond to requests

While the server runs on port 3500.

It did work during the Router video (where I manually wrote anything you did).

DA
DA
8 months ago

Hi, Dave! First of all – thank you for all the great tutorials!

I have a question about response data transformation. Should it be done in the controller layer or should there be an additional "service" layer between the controller and the model?

Thanks!

Mehdi
8 months ago

why u make video ?????

KUNHO KIM
8 months ago

I have a question on part 14:20. When you run employee.firstname = req.body.firstname, wouldnt it mutate the existing employee object in the existing array? In that case isnt it unneccesary to remove the object from array and add it again?

Sona Mohialdin
8 months ago

So good tutorial thank you

Paresh B. Patel
8 months ago

Great tutorial on getting started with Express using the MVC Pattern. Thanks, Dave

{2022-06-10}

FAL
FAL
8 months ago

Thanks Dave, great work !

alireza hekmati
8 months ago

🚀