MVC In Express

MVC In Express

The Model View Controller pattern, or MVC can be implemented in express with ease. If you were unaware MVC is just a way to structure your project when creating an api with express. Dividing the logic into three separate parts makes your code easier to scale and maintain. We start out by creating an express server like normal and then we begin structuring the project.

Once you have an express server created, head to whatever folder your index.js is and create the folders “models”, “controllers”, and “routes” if you do not have them already. Notice we did not create a “views” folder. That is because the views are typically handled by some frontend. We will implement one later, but for now it’s not necessary. Let’s start implementing the logic of a get request inside a controller and show how Mvc is structured in express.

MVC Controllers In Express

For MVC in express, the controllers are where we store logic that happens when we make a request to a route in our api. First let’s go to our controllers directory and create a new file for logic that gets all products on a database and name it Products. Inside of the file let’s write the following code:

MVC In Express

Now that we have our logic defined, let’s refactor our code from inside of the routes folder. We now import our controller and replace the previous function with the new one. It looks like this:

MVC Models

The models directory is where we define the schemas for the objects in our database. You could use whatever method you like, but I will be using mongoose for this tutorial. I won’t go too deep into mongoose or MongoDB here, but if you follow along you can easily understand the concept. MVC is just a way to structure the project so it doesn’t matter what technology you use. Let’s add a file in our models directory named Products. This is what a schema like that might look like in mongoose:

MVC In Express

As you can see, you can easily adapt this to using an sql server or even just json if you’d like. MVC is just a way to structure your projects in a way that will be much easier to take care of as you add more logic into your applications. It is widely used by software engineers and in some cases it is expected you understand MVC when applying for jobs in the industry. Now that you understand how MVC works, It might be a good next step to check out mongoose in express. Until then thanks for reading and comment any questions below.

Leave a Comment

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