MongoDB

Create a RESTfull Application Using Nodejs, Express and MongoDB

Create a restful API nodejs mongodb express

In the previous MongoDB tutorial, we have introduced Mongoose and learned how we can interact with MongoDB database using Mongoose. Now in this tutorial, we are going to create the simple RESTful application using Node.js, Express, and MongoDB. This application will take inputs from users and then it will save that inputs in the MongoDB database.

RESTful application using Node.js, Express, and MongoDB

In this lesson, we are going deeper into Node.Js web applications. Here we are going to use Node.js, Express, and MongoDB, make sure that you are familiar with all these technologies. If you are not then you can review our previous lessons where we have covered all these technologies.

What is RESTful API?

According to Wikipedia Representational State Transfer also known as REST is an architectural style which is used to develop web services. A RESTful API provides an interface to the application and allow the application to uses HTTP requests to GET, PUT, POST and DELETE data. Here we will be using GET to retrieve data, POST to create data, PUT to update and change data and we will use DELETE to delete data.

So we will us RESTful API to define when we are going to add data into our database and when we are going to retrieve data from our database.

Creating Node.JS Application:

We need to make sure that we have Nodejs and MongoDB installed in our operating system. To get started we need to create the new directory, I am creating a folder with name ‘webapp’. After creating the folder open the command prompt in that directory and create the package.JSON file using ‘npm init’ command. Then create a JavaScript file, in our case we have created the app.js file.

After creating the app.js file, we are going to install express framework in the ‘weapp’ folder directory, simply run the following command.

>npm install express --save      

This command will install the express framework and add the module to the package.json file. Here is the screenshot of our package.json below:

RESTfull Application Using Nodejs: Create PackageJSON file nodejs Mongodb

Now we are going to require in the Express framework in our project which will include all the code and content of the express framework in our application. Then we are going to save express in the app variable. Here is the code below:

var express = require("express");
var app = express()

Now we are going to define a port ‘3000’ that we are going to use for this web application. Then we will define the first route

var port = 3000;
app.get("/", (req, res) => {
res.send("Hello World");
});      

Now let’s start the server and tells it to listen on port 3000.

app.listen(port, () => {
console.log("Server listening on port " + port);
});

 

After setting up the server, we need to test it. Now open the command prompt in the web app directory and type ‘node app.js’ command to run the server.

 

Creating Server using Nodejs and MongoDB

 

The server is started, now open your browser and navigate to http://localhost:3000, you will see the following output.

 

NodeJS Hello World

Creating a simple Website:

Now let’s go ahead and create simple HTML page which consist of two inputs. Here is the code below for the html page.

 

<!DOCTYPE html>
<html>
<head>
<title>WebApp</title>
</head>
<body>
<h2>Post Page</h2>
<form>
<input type="text" name="title" placeholder="Enter Title Here..." required><br><br>
<textarea rows="4" cols="50" name="description" placeholder="Write Content here..." required></textarea>
<input type="submit" value="Add Post">
</form>
</body>
</html>

 

This is a simple HTML code, here we have taken three input in which two is text box while one input is ‘Add Post’ button. Now we are going to call this HTML page in our app.js page and we are going to render this page on our web application. We will replace the following code:

 

app.get("/", (req, res) => {
res.send("Hello World");
});

 

With this app.use  code.

 

app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});

 

Now restart the server using the command prompt and then open your browser and navigate to the URL (http://localhost:3000/). this is how our web application would look like:

 

Display HTML page Using nodejs MongoDB

 

Connecting the MongoDB database to our Application:

Now we are connecting our application with database, first, make sure that we have MongoDB installed in our operating system. Now we are using a module Mongoose which will help us to connect our application to MongoDB database. To install Mongoose write the following command in your command prompt

>npm install mongoose –save

Here –save will add the dependencies in our package.json file.

Now after installing the Mongoose module, now we need to connect our application to the database. To do that we need to require in the Mongoose module in our app.js file.

var mongoose = require("mongoose"); 

After installing and require in mongoose module, now we are going to create the database and going to run our database on port 27017 which is by default of MongoDB. We first tell the location of the database and then name that database. Here is the code below:

mongoose.connect("mongodb://localhost:27017/postdb", { useNewUrlParser: true }); 

Here, ‘postdb’ is the database name.

Create Database Schema:

In the previous lesson, we have discussed in detail that how we can create the database schema. If you are not familiar with the database schema, you can view our previous tutorial.

So schema is basically a structure or format of the database, now we are going to create a very simple schema with only two fields. Here is the code for database schema below:

 

var postschema = new mongoose.Schema({
title: String,
description: String
});  

 

This is the schema for our database ‘postdb’. Once we have defined the schema, then we need to convert our ‘postschema’ into a model. To do so, we pass it into the mongoose.model(modelName, schema). Here is the code that you will add next to schema code:

 

var postdata = mongoose.model("postdata", postschema, "postdata");  

Creating RESTful API:

After creating the connection to the database and creating the schema for our database. Now we need to create a mechanism which is used to add data to the database. As we have discussed earlier in this tutorial that data can be added and retrieve through RESTful API. Now we need to create an endpoint to send data to the server then the data will be stored in the database.

 

Creating an Endpoint:

Earlier in this post, I have created an HTML page with single input form, now we are going to create an endpoint to listen to that data and then it will store that data in the database.

Earlier in this tutorials, we have created a ‘GET’ verb to display an HTML page, now we are going to do same thing and instead of using ‘GET’, we are going to use ‘POST’. This is how our endpoint code will look like.

 

app.post("/addpost", (req, res) => {
//bunch of code for saving data into the database

});  

Add Middleware Module:

In our index page we have taking two input with name ‘title’ and ‘description’, now we need to store this data in the database. Before that, we need to capture this data and then convert it into JSON.

So to parse that data we need to install the body-parser module. This is a middleware module and will help us to convert our data into JSON format. So open command prompt in your app directory and to install body-parser run the following command in your command prompt window:

 

>npm install body-parser --save 

 

After installing the body-parser module, now we need to require in that module in our app.

 

var bodyParser = require('body-parser');  

 

Now, we are going to configure body-parser module which will help us to pass to pass data to server and convert the ‘title’ and ‘description’ data in the JSON format. To do that add the following body-parser middleware code in your application file:

 

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));   

Saving data in the database:

So the middleware module body-parser, convert the data in the form of JSON, while module mongoose will take that JSON format object and then store that object in the database. Now we need to create a new instance to save the data in the database. We will pass the user input to this instance then we will run the ‘save’ command. We will add the code in the endpoint method, this is how our final endpoint will look like:

 

app.post("/addpost", (req, res) => {
var myData = new postdata(req.body);
myData.save()
.then(item => {
res.send("Title and Description saved to database’");
})
.catch(err => {
res.status(400).send("saving data failed");
});
});

Testing Application:

Now go ahead and save your code. Then open your command prompt window in your webapp directory and run the app.js file. To run the application, write the command node app.js in your command prompt and hit enter. It will start the server, now open the browser and navigate to the URL http://localhost:3000. It will display the HTML index page with two text box and an ‘Add Post’ button. Here is the output below:

 

Store data in the database MongoDB

 

Now write some text in the title and description textbox and then click on ‘Add Post’ button. If it will successfully save the title and description, then it will redirect you to ‘addpost’ page and display the message ‘Title and Description saved to database’. Here we have written the following text in the input fields and then hit Add Post button

 

Store content in the database MongoDB

 

Now when I hit the Add Post button it displays the following screen:

 

MongoDB Save data in the database

 

Now to check whether the data stored in the database or not, we need to open another command prompt window and then run the mongo command. Then we will write the ‘show DBS’ command to display all the database list.

 

Display data of the database MongoDB NOdejs

 

Now we will select the ‘postdb’ which we have created for this web application, go ahead and write the command ‘use postdb’ in your command prompt window. Then write the following command to display all the data of the postdb database.

 

>db.postdata.find()       

 

It will display the following output where you can notice that it added the data in our database. Here is the illustration below:

 

Find the data MongoDB Nodejs

 

Conclusion:

In this Nodejs and MongoDB tutorial, we have seen that how we can create a RESTful web application using Nodejs, Express, and MongoDB. In this simple web application, we have seen that how we can take input from users and then how can we store that inputs in the database.

You can have a look at the code as well.

1 Comment

Most Popular

To Top