The Model Layer in Express.js

You may have noticed that we neglected many details in the previous lesson. For example,

javascript
1app.get("/user/:id", (req, res) => {
2  res.send("Show user");
3});

When a GET request is sent to route /users/:id, a response containing the message "Show user" will be returned. But of course, there is still a lot we need to do to actually display the user info.

For example, JavaScript will need to check the database and retrieve the right user data based on the id parameter. The retrieved raw data might need to be processed based on your project's specific needs. The processed data will then be embedded into an HTML page and transferred to the client as the response body.

The MVC architecture

In practice, a web application is often split into three layers: model, view, and controller, so that you don't have to put everything into one single file.

The model layer is in charge of interacting with the database, and it should provide methods to get, create, modify, and delete records in the corresponding database table.

The view layer is the frontend part of the app. It is just HTML, but with some programming features included, because sometimes you'll need to embed variables, if statements, and even loops inside the view layer, as you will see later.

The controller layer is your application's command center, connecting the model and view layers. In most cases, its job involves getting data from the database through the model layer, and passing it to the view layer to be rendered.

It might also go the other way, receiving data from the view layer, and passing it to the model so that data can be safely stored inside a database. In the process, the controller might need to perform certain actions on the retrieved data.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉