Getting Started with Nest.js

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

If you have ever worked on a Node.js application before, either built a REST API or an enterprise application, you must have realised how tedious and daunting it was to maintain, especially whenever the application start to scale. The more you add new features to the application, the larger the codebase.

Table of Contents

Creating a proper structure for such application can result into serious headache if not properly managed, especially as a result of application specific configurations. This is why Nest.js was created.
Nest.js was built mainly to eliminate disorganized codebases and give Node.js application a moderate and reasonable structure out of the box. Heavily inspired by Angular, Nest.js was built with TypeScript and uses Express.js under hood. This rightly makes it compatible with the majority of express middleware.

In this post, I will introduce and take you through the process of getting started with Nest.js. You will learn about several ways to install the framework on your machine and why you need to consider using it for your next project. In the process of doing this, you will create a very simple RESTful API that enables users to fetch, create and delete books in a bookstore.

This is a very simple application but yet broad enough to give you comprehensive insight on how to craft an application with Nest.js.

Prerequisites

Familiarity with TypeScript and a reasonable knowledge of JavaScript will help you get the best out of this tutorial. Experienced with building applications with Angular will be a plus but not a requirement as the article will give you a proper guide on how to easily begin.

You need to install Node and npm. It is advisable to also install nodemon globally on your machine.

Overview of Nest.js and why use it

Nest.js is a server-side Node.js framework for building efficient, reliable and scalable applications. Built by Kamil and backed by quite a number of reputable organizations and individuals.

Creating a proper structure for such application can result into serious headache if not properly managed, especially as a result of application specific configurations. This is why Nest.js was created.
Fully built with TypeScript, it comes with the benefits of code type checking and dependency injection which helps to facilitate the process of development of applications. If you are conversant with the structure of Angular applications, you are going to feel so comfortable with the key concepts of Nest.js and getting started with it will be quite an easy task. Anyways, this post will provide you with the required details needed to start building applications with Nest.js.

In addition, the following list shows some of the benefits of Nest.js as explained here by Kamil:

Now that you have been briefed about this awesome framework, let’s take a look at the building blocks of Nest.js.

Building blocks of Nest.js

The following are the building blocks used when building Nest.js applications:

Controllers

Typical to most web frameworks, controllers in Nest.js are responsible for handling any incoming requests and returning responses to the client side of the application. For example, if you make an API call to a particular endpoint, say /home, the controller will receive this request and based on the available resources, it will returned the appropriate response.

Nest.js was structured in a way that the routing mechanism is able to control which controller will be responsible for handling a particular request.

Defining a basic controller in Nest.js is as good as creating a TypeScript file and including a decorator @Controller() just like the code snippet below:

  // users.controller.ts 

import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
 @Get()
 findAll() { 
   return 'This will return all the users';
 }
}

The prefix of users within the Controller decorator will prompt the UsersController to handle any /users GET request within an application and return the appropriate response as specified. Other HTTP request handled by the controller includes POST , PUT, DELETE as we will see later in the tutorial.

Once a controller is created, it needs to be added to the module definition before Nest.js can easily recognise it. This could be the root ApplicationModule or any other module created within the application. More about this in the module section of this post.

Providers

As mentioned earlier, Nest.js was heavily inspired by Angular and similar to an Angular application, one can easily create a provider and inject it into controllers or other providers too as well. These providers are also called services and based on the philosophy of Nest.js, it was designed to abstract any form of complexity and logic to a class called service.

A service provider in Nest.js is just a normal JavaScript class with a special @Injectable() decorator at the top.

For example, you can simply create a service to fetch users as shown below:

    // users.service.ts

import { Injectable } from '@nestjs/common';
import { User } from './interfaces/user.interface';

@Injectable()
export class UsersService {
  private readonly users: User[] = [];

  create(user: User) { 
    this.users.push(user);   }

  findAll(): User[] {
    return this.users;
  }
}

The provider created above is a class with two methods create() and findAll(), which can be used to create and return all users respectively. And to easily help with type checking an interface was used to specify the type of elements that should be received by the methods.

Modules

Modules are more like the most important basic building block in Nest.js. They are TypeScript files decorated with @Module decorator. This attached decorator provides metadata that Nest makes use of to organize the application structure. With modules you can easily group related files into one.

Each Nest.js application must have at least one module, usually referred to as the root module. This root module is the top-level module and usually enough for a small application but it is advisable to break a large application into multiple modules as it helps to maintain the structure of the application.

If you have an application that manages a lot of data or functionality about users , we can group both the controller, services and other related files into a single module, say UsersModule for example:

import { Module } from '@nestjs/common';
import { UsersController } from './users.controller.ts';
import { UsersService } from './users.service.ts';

@Module({
  controllers: [UsersController],
  providers: [UsersService]
})

export class UsersModule {}

From the preceding file, we are exported a UsersModule that contains both the UsersController and UsersService. With this in place, we can then proceed to import and use the UsersModule within the root module of the application as shown in the following code snippet:

...
import { UsersModule } from './users/users.module';

@Module({
  ...
})

export class AppModule { }

Other important concepts

DTO

Data transfer object is an object that defines how data will be sent over the network.

Interfaces

TypeScript interfaces are used for type-checking and defining the types of data that can be passed to a controller or a Nest service.

Dependency injection

Dependency injection is a design pattern used to increase efficiency and modularity of applications. It is often used by the biggest frameworks to keep code clean and easier to use. Nest.js also makes use of it to basically create coupled components.

With this pattern, it is very easy to manage dependencies between building blocks like controllers, providers and modules. The only thing required is to define the dependency for example a UsersService() in the constructor of a controller as shown here:


...
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService){}
 ...
}

With some of these concepts briefly covered, you can now proceed to the next section, where you will put all the knowledge gained so far in this post into use as you will learn how to seamlessly build a RESTful API using Nest.js.

What you will build with Nest.js

As stated earlier in this post, you will create a sample application that will help you get a good grasp on some of the core concepts of Nest.js.

This application will be specifically for a bookstore. At the end of the post you would have created a micro-service that will enable users to create and add a new book with few descriptions to an existing list of books. This could be from a database, but to ensure simplicity in this post, we won’t really be connecting our application to a database yet. But instead, we will make use of a mock data of books and once a new book is created, we will push and add it to the list.

Installing Nest.js

In order to easily scaffold a new Nest.js application, you will need to globally installed Nest CLI. It is a command line interface tool specifically created to amongst other things, help to craft a new Nest.js app in no time and provide access to ( built in generators ) several commands to generate different files and produce a well-structured application.

Apart from using the CLI tool, you can also install a new Nest.js application by cloning the starter project from GitHub using Git, but for the purpose of this tutorial run the following command to install the Nest CLI:

npm i -g @nestjs/cli

This will give you access to the nest command for project installation and other project specific commands.

Next, run the command below to install a new project named bookstore-nest within your development folder:

nest new bookstore-nest

You will be asked few questions during the installation, just follow the prompt and respond accordingly. Next, once the installation is complete, change directory into the newly created project and start the application with:


// change directory
cd bookstore-nest

// start the application
npm run start

or better still, run the command below in order to use Nodemon for the project:


// start the application using nodemon
npm run start:dev

Navigate to http://localhost:3000 from your favorite browser, you will see the Hello World! message as shown here:

Generate a module

First you will start by generating a module for the bookstore. To do this, you will leverage the inbuilt file generator using Nest CLI. Run the following command to scaffold a new module for the application:

nest generate module books

The command above will create a new folder named books within the src folder. Also within the books folder you will find a books.module.ts file.


// ./src/books/books/module.ts

import { Module } from '@nestjs/common';
@Module({})
export class BooksModule {}

This was generated by the command and the module has also been added to the app.module.ts which happens to be the root module of the application.

Create routes

Next, you will create routes for the endpoints. As mentioned earlier, routes are in controllers, so you need to create controllers that will handle individual endpoints. Again, use Nest CLI to generate your controllers, run the following command:

nest generate controller books

This will create a controller inside the books folder. Since we won’t really be connecting to the database for now, create a sample mock data for the bookstore. Under the src folder, create a subfolder named mocks and within the newly created folder, create a new TypeScript file named books.mock.ts and paste the following code in it:


// ./src/mocks/books.mock.ts
export const BOOKS = [
    { id: 1, title: 'First book', description: "This is the description for the first book", author: 'Olususi Oluyemi' },
    { id: 2, title: 'Second book', description: "This is the description for the second book", author: 'John Barry' },
    { id: 3, title: 'Third book', description: "This is the description for the third book", author: 'Clement Wilfred' },
    { id: 4, title: 'Fourth book', description: "This is the description for the fourth book", author: 'Christian nwamba' },
    { id: 5, title: 'Fifth book', description: "This is the description for the fifth book", author: 'Chris anderson' },
    { id: 6, title: 'Sixth book', description: "This is the description for the sixth book", author: 'Olususi Oluyemi' },
];

Setting up service

Next, you will create a service to hold all the logic for the bookstore. Run the following command to generate a service:

nest generate service books

This command will create a new file named books.service.ts within ./src/books folder.

Get books

Next, open the newly created file and paste the following:


//  ./src/books/books.service.ts

  import { Injectable, HttpException } from '@nestjs/common';
  import { BOOKS } from '../mocks/books.mock';

  @Injectable()
  export class BooksService {
      books = BOOKS;

      getBooks(): Promise<any> {
          return new Promise(resolve => {
              resolve(this.books);
          });
      }
      getBook(bookID): Promise<any> {
          let id = Number(bookID);
          return new Promise(resolve => {
              const book = this.books.find(book => book.id === id);
              if (!book) {
                  throw new HttpException('Book does not exist!', 404);
              }
              resolve(book);
          });
      }
  }

First, you imported the requires modules from Nest.js and also BOOKS from the mock data you created earlier.

Next, you created two different methods named getBooks() and getBook() to retrieve the list of books from the mock data and to fetch just one book using the bookID as a parameter.

Add book

Next, add the method below to the /src/books/books.service.ts immediately after the getBook() method:


//  ./src/books/books.service.ts

import { Injectable, HttpException } from '@nestjs/common';
import { BOOKS } from '../mocks/books.mock';
@Injectable()
export class BooksService {
    books = BOOKS;
    ...
    addBook(book): Promise<any> {
        return new Promise(resolve => {
            this.books.push(book);
            resolve(this.books);
        });
    }
}

The method above will be used to push a new book to the existing list

Delete book

Finally, add the last method to delete a particular book using the bookID as a parameter:


//  ./src/books/books.service.ts

import { Injectable, HttpException } from '@nestjs/common';
import { BOOKS } from '../mocks/books.mock';
@Injectable()
export class BooksService {
    books = BOOKS;
    ...
    deleteBook(bookID): Promise<any> {
        let id = Number(bookID);
        return new Promise(resolve => {
            let index = this.books.findIndex(book => book.id === id);
            if (index === -1) {
                throw new HttpException('Book does not exist!', 404);
            }
            this.books.splice(1, index);
            resolve(this.books);
        });
    }
}

Inject service into controller

Here, you will use dependency injection design pattern to pass the BooksService into the BooksController through a constructor. Open the BooksController created earlier and paste the following code in it:


// ./src/books/books.controller.ts

import { Controller, Get, Param, Post, Body, Query, Delete } from '@nestjs/common';
import { BooksService } from './books.service';
import { CreateBookDTO } from './dto/create-book.dto';

@Controller('books')
export class BooksController {
    constructor(private booksService: BooksService) { }

    @Get()
    async getBooks() {
        const books = await this.booksService.getBooks();
        return books;
    }

    @Get(':bookID')
    async getBook(@Param('bookID') bookID) {
        const book = await this.booksService.getBook(bookID);
        return book;
    }

    @Post()
    async addBook(@Body() createBookDTO: CreateBookDTO) {
        const book = await this.booksService.addBook(createBookDTO);
        return book;
    }

    @Delete()
    async deleteBook(@Query() query) {
        const books = await this.booksService.deleteBook(query.bookID);
        return books;
    }
}

Here in this controller, first, the important modules were imported from @nestjs/common and you also import both the BooksService and CreateBookDTO respectively. CreateBookDTO is a data transfer object, a TypeScript class created for type-checking and to define the structures of what an object looks like when creating a new book. We will create this DTO in a bit.

Next, you used constructor to inject the BooksService into the controller and created four different methods which are:

Each of the methods has a special decorator attached to it, which makes it very easy to route each HTTP request to a specific method within the controller.

The DTO

In the previous section, you made use of a data transfer object called CreateBookDTO. To set it up, navigate to the ./src/books folder and create a new subfolder name dto. Next, within the newly created folder, create another file and call it create-book.dto.ts and paste the following in it:


// ./src/books/dto/create-book.dto.ts

export class CreateBookDTO {
    readonly id: number;
    readonly title: string;
    readonly description: string;
    readonly author: string;
}

You are almost done with the application, the next line of action is to take a look at the BooksModule and update it accordingly. You will do that in the next section.

Update the books module

Navigate back to the BooksModule created earlier and update it with the code below:


// ./src/books/books.module.ts

import { Module } from '@nestjs/common';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';
@Module({
  controllers: [BooksController],
  providers: [BooksService]
})
export class BooksModule {}

Test the application

Start the application again if it is not running at the moment with:

npm run start

and use postman to test the API

Get Books

Get book using bookID

Create a new book

Delete a book

Conclusion

We have barely scratched the surface on what Nest.js has to offer the Node.js world in this post. To get more conversant with this awesome framework, first, we took a quick look at the fundamentals and basic building blocks of Nest.js and then proceeded to build a RESTful API where you also learnt about dependency injection amongst other things.

I hope this tutorial as given you enough information to try out Nest.js for your next application. Feel free to drop your thoughts in the comment section below and find the complete source code of this tutorial here on GitHub.

Learn More

The Complete Node.js Developer Course (2nd Edition)

Learn and Understand NodeJS

Node JS: Advanced Concepts

GraphQL: Learning GraphQL with Node.Js

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

Beginner Full Stack Web Development: HTML, CSS, React & Node

Node with React: Fullstack Web Development

MERN Stack Front To Back: Full Stack React, Redux & Node.js

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

How to Use Express.js, Node.js and MongoDB.js

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Creating a Node Application

To get started I would recommend creating a new database that will contain our application. For this demo I am creating a directory called node-demo. After creating the directory you will need to change into that directory.

mkdir node-demo
cd node-demo

Once we are in the directory we will need to create an application and we can do this by running the command
npm init

This will ask you a series of questions. Here are the answers I gave to the prompts.

The first step is to create a file that will contain our code for our Node.js server.

touch app.js

In our app.js we are going to add the following code to build a very simple Node.js Application.

var express = require("express");
var app = express();
var port = 3000;
 
app.get("/", (req, res) => {
&nbsp;&nbsp;res.send("Hello World");
});
 
app.listen(port, () => {
  console.log("Server listening on port " + port);
});

What the code does is require the express.js application. It then creates app by calling express. We define our port to be 3000.

The app.use line will listen to requests from the browser and will return the text “Hello World” back to the browser.

The last line actually starts the server and tells it to listen on port 3000.

Installing Express

Our app.js required the Express.js module. We need to install express in order for this to work properly. Go to your terminal and enter this command.

npm install express --save

This command will install the express module into our package.json. The module is installed as a dependency in our package.json as shown below.

To test our application you can go to the terminal and enter the command

node app.js

Open up a browser and navigate to the url http://localhost:3000

You will see the following in your browser

Creating Website to Save Data to MongoDB Database

Instead of showing the text “Hello World” when people view your application, what we want to do is to show a place for user to save data to the database.

We are going to allow users to enter a first name and a last name that we will be saving in the database.

To do this we will need to create a basic HTML file. In your terminal enter the following command to create an index.html file.

touch index.html

In our index.html file we will be creating an input filed where users can input data that they want to have stored in the database. We will also need a button for users to click on that will add the data to the database.

Here is what our index.html file looks like.

<!DOCTYPE html>
<html>
  <head>
    <title>Intro to Node and MongoDB<title>
  <head>

  <body>
    <h1>Into to Node and MongoDB<&#47;h1>
    <form method="post" action="/addname">
      <label>Enter Your Name<&#47;label><br>
      <input type="text" name="firstName" placeholder="Enter first name..." required>
      <input type="text" name="lastName" placeholder="Enter last name..." required>
      <input type="submit" value="Add Name">
    </form>
  <body>
<html>

If you are familiar with HTML, you will not find anything unusual in our code for our index.html file. We are creating a form where users can input their first name and last name and then click an “Add Name” button.

The form will do a post call to the /addname endpoint. We will be talking about endpoints and post later in this tutorial.

Displaying our Website to Users

We were previously displaying the text “Hello World” to users when they visited our website. Now we want to display our html file that we created. To do this we will need to change the app.use line our our app.js file.

We will be using the sendFile command to show the index.html file. We will need to tell the server exactly where to find the index.html file. We can do that by using a node global call __dirname. The __dirname will provide the current directly where the command was run. We will then append the path to our index.html file.

The app.use lines will need to be changed to
app.use("/", (req, res) => {   res.sendFile(__dirname + "/index.html"); });

Once you have saved your app.js file, we can test it by going to terminal and running node app.js

Open your browser and navigate to “http://localhost:3000”. You will see the following

Connecting to the Database

Now we need to add our database to the application. We will be connecting to a MongoDB database. I am assuming that you already have MongoDB installed and running on your computer.

To connect to the MongoDB database we are going to use a module called Mongoose. We will need to install mongoose module just like we did with express. Go to your terminal and enter the following command.
npm install mongoose --save

This will install the mongoose model and add it as a dependency in our package.json.

Connecting to the Database

Now that we have the mongoose module installed, we need to connect to the database in our app.js file. MongoDB, by default, runs on port 27017. You connect to the database by telling it the location of the database and the name of the database.

In our app.js file after the line for the port and before the app.use line, enter the following two lines to get access to mongoose and to connect to the database. For the database, I am going to use “node-demo”.

var mongoose = require("mongoose"); mongoose.Promise = global.Promise; mongoose.connect("mongodb://localhost:27017/node-demo");

Creating a Database Schema

Once the user enters data in the input field and clicks the add button, we want the contents of the input field to be stored in the database. In order to know the format of the data in the database, we need to have a Schema.

For this tutorial, we will need a very simple Schema that has only two fields. I am going to call the field firstName and lastName. The data stored in both fields will be a String.

After connecting to the database in our app.js we need to define our Schema. Here are the lines you need to add to the app.js.
var nameSchema = new mongoose.Schema({   firstName: String,   lastNameName: String });

Once we have built our Schema, we need to create a model from it. I am going to call my model “DataInput”. Here is the line you will add next to create our mode.
var User = mongoose.model("User", nameSchema);

Creating RESTful API

Now that we have a connection to our database, we need to create the mechanism by which data will be added to the database. This is done through our REST API. We will need to create an endpoint that will be used to send data to our server. Once the server receives this data then it will store the data in the database.

An endpoint is a route that our server will be listening to to get data from the browser. We already have one route that we have created already in the application and that is the route that is listening at the endpoint “/” which is the homepage of our application.

HTTP Verbs in a REST API

The communication between the client(the browser) and the server is done through an HTTP verb. The most common HTTP verbs are
GET, PUT, POST, and DELETE.

The following table explains what each HTTP verb does.

HTTP Verb Operation
GET Read
POST Create
PUT Update
DELETE Delete

As you can see from these verbs, they form the basis of CRUD operations that I talked about previously.

Building a CRUD endpoint

If you remember, the form in our index.html file used a post method to call this endpoint. We will now create this endpoint.

In our previous endpoint we used a “GET” http verb to display the index.html file. We are going to do something very similar but instead of using “GET”, we are going to use “POST”. To get started this is what the framework of our endpoint will look like.

app.post("/addname", (req, res) => {
 
});
Express Middleware

To fill out the contents of our endpoint, we want to store the firstName and lastName entered by the user into the database. The values for firstName and lastName are in the body of the request that we send to the server. We want to capture that data, convert it to JSON and store it into the database.

Express.js version 4 removed all middleware. To parse the data in the body we will need to add middleware into our application to provide this functionality. We will be using the body-parser module. We need to install it, so in your terminal window enter the following command.

npm install body-parser --save

Once it is installed, we will need to require this module and configure it. The configuration will allow us to pass the data for firstName and lastName in the body to the server. It can also convert that data into JSON format. This will be handy because we can take this formatted data and save it directly into our database.

To add the body-parser middleware to our application and configure it, we can add the following lines directly after the line that sets our port.

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Saving data to database

Mongoose provides a save function that will take a JSON object and store it in the database. Our body-parser middleware, will convert the user’s input into the JSON format for us.

To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user’s input. Once we have it then we just need to enter the command “save”.

Mongoose will return a promise on a save to the database. A promise is what is returned when the save to the database completes. This save will either finish successfully or it will fail. A promise provides two methods that will handle both of these scenarios.

If this save to the database was successful it will return to the .then segment of the promise. In this case we want to send text back the user to let them know the data was saved to the database.

If it fails it will return to the .catch segment of the promise. In this case, we want to send text back to the user telling them the data was not saved to the database. It is best practice to also change the statusCode that is returned from the default 200 to a 400. A 400 statusCode signifies that the operation failed.

Now putting all of this together here is what our final endpoint will look like.

app.post("/addname", (req, res) => {
  var myData = new User(req.body);
  myData.save()
    .then(item => {
      res.send("item saved to database");
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});
Testing our code

Save your code. Go to your terminal and enter the command node app.js to start our server. Open up your browser and navigate to the URL “http://localhost:3000”. You will see our index.html file displayed to you.

Make sure you have mongo running.

Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database like below.

Access to Code

The final version of the code is available in my Github repo. To access the code click here. Thank you for reading !