4elements

blog

Build Web Applications Using Node.js

Introduction

Aside from building APIs, Node.js is great for building standard web applications. It has powerful tools to meet the taste of web developers. In this tutorial, you will be building a web application that can serve as a local library.

While building you will learn about some types of middleware, you will see how to handle form submission in Node.js, and you will also be able to reference two models.

You required the two routes you will be making use of in building this application. You will create the routes file shortly. The required routes are assigned as values to two different variables which are used when setting up the middleware for your routes.

You set Mongoose to use global.Promise. The variable MongoDB is assigned the MONGODB_URI of your environment or the path to your local mongo server. This variable is passed as an argument to connect to the running MongoDB server.

You set up session middleware using express-session. This middleware is important as you will be displaying flash messages in some parts of your application.

You set up middleware for validation. This middleware will be used to validate form input, ensuring that users of the application do not submit an empty form. The validation uses a package installed, express-validator.

You set up middleware which will come in handy when displaying flash messages. This middleware makes use of connect-flash.

The routes for the application are set up to make use of the routes file you required. Requests pointing to /genres and /books will make use of the genres and books routes files respectively. At this moment you have not created the routes files, but you will do that soon.

Book and Genre Model

The Book Model will make use of Mongoose Schema to define how the books will be structured. Create a directory called models, and a new file called Book.js. Here is what it looks like.

Here you have four fields. The last field is used to store the genre each book belongs to. The genre field here references the Genre model, which will be created next. That's why the type is set to Schema.Types.ObjectId, which is where the ids of each referenced genre will be saved. ref specifies the model you are referencing. Note that genre is saved as an array, meaning that a book can have more than one genre.

This route gets called whenever requests are made to /genres. Here you call the find method on your Genre model to obtain all the genres that have been created. These genres are then rendered on a template called genres. Let's go ahead and create that, but first, update your layout.pug to look like this:

This will give your views a nice structure to aid navigation. Now create a view file called genre.pug. In this file, you will loop through the genres created and output each genre in an unordered list.

The job of this router is to simply display the page for adding new routes. This router gets called whenever requests are made to /genres/add path.

This router handles the submission of the form. When the form is submitted, we check to ensure that a name is entered by the user. If no name is entered, the page is re-rendered. If the checks are good to go, the genre is saved and the user is redirected to the /genres page.

In the first router, you are displaying the /addBooks page. This router is called when a request is made to /add path. Since books added are supposed to have genres, you want to display the genres that have been saved to the database.

const genres = Genre.find({}).exec()
.then((genres) => {

The code above finds all the genres in your database and returns them in the variable genres. With this, you will be able to loop through the genres and display them as checkboxes.

The second router handles the submission of the form. First, you check the body of the request to ensure that some fields are not empty. This is where the express-validator middleware you set in app.js comes handy. If there are errors, the page is re-rendered. If there are none, the new Book instance is saved and the user is redirected to the /books page.

Let's go ahead and create the views for this.

Create a new view file called addBooks.pug. Note that the name of the view matches the first parameter given to res.render. This is because you are rendering a template. During redirection, you simply pass the path you want to redirect to, as you did with res.redirect('/books').

The important thing to note here is the form action and method. When the submit button is clicked, you are making a POST request to /books/add. One other thing—once again you loop through the collection of genres returned and display each of them.

Book Show Route and View

Let us drop in the route to handle the requests made to each books page. While you are there, it is important to export your module too.

First, requests made to this router must have an id: the id of the book. This id is obtained from the params of the request using req.params.id. This is used to identify the specific book that should be obtained from the database, as the ids are unique. When the book is found, the genre value of the book is populated with all the genres that have been saved to this book instance. If all goes well, the book view is rendered, else an error is thrown.

Conclusion

Now you know how to build a standard web application in Node.js, not just a simple to-do app. You were able to handle form submission, reference two models, and set up some middleware.

You can go further by extending the application—try adding the ability to delete a book. First add a button to the show page, and then go to the routes files and add a router for this. Note that this is going to be a POST request.

You can also think of more features to add to the application. I hope you enjoyed it.