Building a CRUD App with Node.js, Express.js, and MongoDB πŸ˜Άβ€πŸŒ«οΈ

Building a CRUD App with Node.js, Express.js, and MongoDB πŸ˜Άβ€πŸŒ«οΈ

Β·

9 min read

Introduction:

In today's digital world, building web applications with robust functionality is crucial. One popular approach is creating a CRUD (Create, Read, Update, Delete) application that allows users to perform these fundamental operations on a database. In this blog post, we will explore how to build a CRUD app using Node.js, Express.js, and MongoDB. This powerful trio of technologies provides a scalable and efficient solution for developing web applications. πŸ‘¨πŸ»β€πŸ’»

Prerequisites:

Before we dive into the implementation, make sure you have the following prerequisites installed on your machine:

  1. Node.js and npm (Node Package Manager)

  2. MongoDB (Community Edition or Atlas)

  3. Basic knowledge of JavaScript, Node.js, and MongoDB

  4. Postman πŸ‘¨πŸ»β€πŸ’»

Setting Up the Project:

Let's start by setting up a new project. Open your terminal and follow these steps:

Step 1: Create a new directory for your project.

Step 2: Initialize a new Node.js project.

Step 3: Install the required dependencies. πŸ’»

package.json()

Before starting with the Backend, we need to make a file called '.env', this file will contain data that we want to keep with ourselves and is local to our system for example, the port on which the application will run or the MongoDB URI that every user needs to have their own.

Building the Backend:

Now that we have our project set up, let's start building the backend using Express.js and MongoDB. πŸ‘¨πŸ»β€πŸ’»

Step 1: Create a server.js file in the project's root directory.

Now add a script "dev" to the package.json file as given in the above snapshot.

Set up the constant app using Express.js and make a middleware.

Now connect to MongoDB and check if it is connected or not. If not catch an error.

Let's check for its output.

Once MongoDB is connected we are set to go ahead with our Schema. πŸ’»

MVC:

MVC stands for Model-View-Controller, which is a software architectural pattern commonly used in the development of user interfaces. It provides a way to separate the concerns of an application into three interconnected components:

  1. Model: The model represents the data and business logic of the application. It encapsulates the application's data and defines the operations that can be performed on that data. In other words, the model represents the application's underlying data structure and rules.

  2. View: The view is responsible for rendering the user interface and presenting the data to the user. It displays the information from the model and interacts with the user for input. The view is typically concerned with the presentation logic and does not contain any business logic.

  3. Controller: The controller acts as an intermediary between the model and the view. It handles user input and updates the model accordingly. It receives input from the user via the view, processes that input, and manipulates the model or retrieves data from it. It also updates the view to reflect any changes in the model.

The MVC pattern promotes the separation of concerns and modularity in application development. By separating the responsibilities of data management, user interface presentation, and user input handling, it becomes easier to maintain and modify different components independently. Additionally, it allows for code reusability and promotes a clean and organized codebase.

It's worth noting that MVC is not limited to a specific programming language or framework. It has been widely adopted in various technologies, including web development frameworks like Ruby on Rails, ASP.NET MVC, and Django, as well as desktop application frameworks like JavaFX and Cocoa. πŸ‘¨πŸ»β€πŸ’»

Now, let us work with the todoSchema.

To begin with we need to set a constant Schema using Mongoose, after this, we have to make a new Schema that would include our body of data.

A schema is a structural representation or blueprint that defines the organization, relationships, and constraints of data within a database or information system. It provides a framework for organizing and interpreting data, specifying the fields or attributes that make up a data entity and defining their types, formats, and relationships.

In the context of databases, a schema defines the logical and physical structure of the database, including tables, columns, relationships, indexes, and constraints. It serves as a blueprint for creating, modifying, and accessing the data stored in the database.

Here we have 3 parts for our body which are:

Title: The title of the task which we want to add, should be of type String and it is a required field.

Priority: This will tell us the priority of the task, as in the task is of priority 'first', 'second'. By default, any new task added should be our priority number one.

DueDays: This field is very important for a todo-list, the task is due for how many days, the Type will be Number and yes it is a required field.

Now we will export the Schema using the module.exports and model function of Mongoose.

Now let's move on to controllers.

A controller is one of the key components that make up the architecture. The controller is responsible for handling user input, coordinating the flow of data, and updating the model and view accordingly.

The main purpose of a controller is to receive input from the user or external sources, process that input, and determine the appropriate actions to take. It acts as the intermediary between the view and the model, facilitating communication and synchronization between them. πŸ‘¨πŸ»β€πŸ’»

Here are some key characteristics and responsibilities of a controller in MVC:

  1. Receives User Input: The controller is responsible for capturing user interactions such as button clicks, form submissions, or other input events. It listens for these events and initiates the corresponding actions.

  2. Orchestrates Actions: Based on the user input, the controller determines the appropriate actions to be performed. It may involve retrieving or modifying data in the model, invoking business logic, or triggering updates in the view.

  3. Updates the Model: The controller interacts with the model to update the data or retrieve information based on the user's input. It invokes the relevant methods or services in the model to perform these operations.

  4. Updates the View: After processing user input and updating the model, the controller communicates with the view to ensure it reflects the updated state. It may pass data from the model to the view and instruct the view on how to render the updated information.

  5. Manages Flow and Navigation: The controller often manages the overall flow and navigation within the application. It determines which view should be presented to the user based on the current state of the application and the actions performed.

By separating the responsibilities of handling user input, managing data, and rendering the user interface, the controller contributes to the maintainability, extensibility, and reusability of the application's code. It promotes a clear separation of concerns and allows for easier modification and testing of individual components within the MVC architecture. πŸ’»

Here's a brief explanation of async and await:

  1. async: The async keyword is used to declare a function or method as asynchronous. An asynchronous function returns a promise, which represents the eventual completion or failure of an asynchronous operation. By marking a function as async, you can use the await keyword inside that function.

  2. await: The await keyword can only be used inside an async function. It is used to pause the execution of the function until a promise is fulfilled or rejected. When encountering the await keyword, the function stops executing and waits for the promise to resolve. This allows other code to run concurrently, improving the responsiveness of the program. 😎

Different Controllers:

  1. getTodo:

    This is the first and foremost constant declared in the controllers, this gives us all the data in the database and sorts it in such an order that the newer ones come above the older ones.

    '.find({}).sort({ createdAt: -1 })' is the function used.

  2. getSingleTodo:

    If we want to get a single Todo detail, we use this as this will give us the details of the todo corresponding to the id which we input.

    '.findById' is the function used.

  3. addTodo/createTodo:

    Now, this is used if want to add a todo to the todo list, the Schema elements are stored in req.body.

    '.create' is the function used.

  4. updateTodo:

    This function is used to update an existing todo from the list, once the id of the todo is input, the corresponding todo can be updated.

    '.findOneAndUpdate' is the function used.

  5. deleteTodo:

    This function is used to delete an existing todo from the list, once the id of the todo is input, the corresponding todo can be deleted.

    '.findOneAndDelete' is the function used.

    Once this is done all the constants are exported. πŸ‘¨πŸ»β€πŸ’»

Now we move to routes in MVC.

Routers act as a middleware layer between the incoming requests and the application logic. They examine the request URL, HTTP method, and any additional parameters to determine which controller method or handler should be invoked to handle the request. Routers provide a way to organize and structure the handling of different routes and HTTP actions within an application.

Typically, routers follow a pattern where you define the route paths and associate them with the appropriate controller methods. For example, in a CRUD application for managing users, you might define routes like /users for fetching all users, /users/:id for retrieving a specific user, /users (POST) for creating a new user, and so on.

When a request is received, the router matches the requested URL and HTTP method to the appropriate route and invokes the associated controller method or handler. The controller is responsible for processing the request, performing the corresponding CRUD operation, and returning the appropriate response.

Routers provide a way to modularize and separate concerns in an application. They help keep the routing logic organized and maintainable, allowing developers to easily add, modify, or remove routes as needed. In many frameworks, routers also provide additional features like middleware support, parameter parsing, route parameter validation, and route grouping. πŸ‘¨πŸ»β€πŸ’»

A constant router is set up by using Express.Router(), this router is used to send requests such as get, post, patch, and delete.

  • '/' is used in cases of post request and get all requests, because there is no need for the 'id' parameter in these 2 requests.

  • '/:id' is used in case of patch and delete requests, where the id parameter is important to update or delete the element corresponding to that id.

Now the 'router' is exported and now we will connect this to our server.js file.

app.use('/api/todolist', todoRoutes) is used to provide a directory to the requests by the router.

Let us now start the application.

Open new terminal and hop into the Backend folder.

Now, start the web app.

And that is it our CRUD app is ready and working, I will put a few Postman snapshots showing the working of our app. 😎

MongoDB Compass shows the data stored. 😎

That is it for this blog, see you in the next one we will add authentication, validation, and error handling. 😎

A youtube video of me making a CRUD application.

GitHub source code:

Conclusion:

In this blog post, we have learned how to build a CRUD app using Node.js, Express.js, and MongoDB. We covered the setup process, connecting to MongoDB, defining routes for CRUD operations, and implementing the necessary database operations. This combination of technologies provides a powerful foundation for building scalable and efficient web applications. Remember to explore and enhance your app by adding authentication, validation, error handling, and more based on your specific requirements. Happy coding!

Did you find this article valuable?

Support Dhyan Tech!! by becoming a sponsor. Any amount is appreciated!

Β