How to build a REST API using MongoDB, Express.js and Node.js

How to build a REST API using MongoDB, Express.js and Node.js

Lets try to make a simple REST API using MongoDB, Express.js and Node.js

You can also find the project in REST_API-MongoDB repository.

Also look at this api url https://restapi-cars.herokuapp.com for getting data https://restapi-cars.herokuapp.com/Cars

Get Started..

  • Open your project folder and in terminal with your current project folder name, enter npm init it will create you a package.json file in your project.

  • In package.json file under scripts add the code:

"start": "nodemon server.js"
  • You will see like:
{
  "name": "rest_api",
  "version": "1.0.0",
  "description": "Rest API using MEN (MongoDB,ExpressJs and NodeJs)",
  "main": "server.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.11.14",
    "nodemon": "^2.0.7"
  }
}

Lets install some packages

  • Express.js: Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It is an open source framework developed and maintained by the Node.js foundation
npm i express
  • Nodemon: nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.
npm i nodemon
  • Cors: The origin(s) to be allowed for making cross-domain requests
npm i cors
  • Mongoose: Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. MongoDB is one of the most popular NoSQL databases in the world.
npm i mongoose
  • Lets write a simple node.js application using express.js and run the server using nodemon
import express from 'express'

var app = express()
var port = process.env.PORT || 8080 

app.get("/", function (req, res){
    res.send( "Welcome to Tutorial of REST API using MongoDB, ExpressJS and NodeJS");
})

app.listen(port)

Now let’s create a database in mongodb

  • Open Mongodb website create a account or if you have an account Login into it.

  • After login top right side you will see a dropdown, click on it and create a new project by clicking on New Project.

  • Add name for you project and click next and then click create project.

  • Now you will redirect to homepage of with your project name.

  • Now we need to create a cluster by clicking on build a cluster.

  • Now we need to select the free version of cluster.

  • After that keep the cloud provider and regions default or you can select any region and click on create cluster.

  • Now it will redirect to homepage and you will see a new cluster is been creating for you, it taker few minutes.

  • When it is live, now we need to create a database by clicking Database Access on right side.

  • And click on Add new Database User and add the username and password for your database or for password click on auto generate password. After that copy the password and save it anywhere it will be used in connect database using node.js application and click on Add Use to save the user.

  • Now we need to have a network access to connect the server and Click on Add IP Address.

  • Now you will see this form popups and click on allow access from anywhere to access this server from any ip address and click on create.

  • Now you will see the status like pending and it will take few seconds and the status will be active.

  • Now click on Cluster you will see it right side.

  • Now click on connect button in the sandbox and you will see three options to select, select connect your application. By default it will show node.js driver and version of that.

  • Now copy the link below and keep it some where in notepad.

    Lets start coding again..

  • Now open the server.js file and create a new varaible calledConnection_url and paste the link here which you have copied above.

var Connection_url = 'mongodb+srv://Rest-API_lmas:<password>@cluster0.gklyj.mongodb.net/<dbname>?retryWrites=true&w=majority'
  • Near &lt;password&gt; add the copied password which you have generated password while creating a database and replace &lt;dbname&gt;with any name or project name without any special-char or spaces.

  • Now lets connect Connection_url with mongoose and also import the mongoose and cors package.

import mongoose from "mongoose"
mongoose.connect(Connection_url, {
   useNewUrlParser: true,
   useCreateIndex: true,
   useUnifiedTopology: true
})
  • Now lets combined all the code:
import express from 'express'
import mongoose from "mongoose"
import Cors from 'cors'

var app = express()
var port = process.env.PORT || 8080 

app.use(express.json())
app.use(Cors())

var Connection_url = 'mongodb+srv://Rest-API_lmas:<password>@cluster0.gklyj.mongodb.net/<dbname>?retryWrites=true&w=majority'

mongoose.connect(Connection_url, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
})

app.get("/", function (req, res){
    res.send( "Welcome to Tutorial of REST API using MongoDB, ExpressJS and NodeJS");
})

app.listen(port)
  • Here app.use(Cors()) and app.use(express.json()) are the middlewares to our application.

  • Now lets create schema for your project.

  • Schema: A “Schema” for a database can be compared with the “Class” in object-oriented programming. Just like a class that provides a blueprint for creating objects in a program, a schema provides a blueprint for creating objects (called documents in MongoDB) in a database.

  • Everything in Mongoose starts with defining a schema. It maps directly to a MongoDB collection and defines the structure of the document within that collection.

    Mongoose allows the following schema types:

  • String

  • Number

  • Date

  • Buffer

  • Boolean

  • Mixed

  • ObjectId

  • Array

  • Decimal128

  • Map

    A Mongoose model is a compiled version of the schema definition that maps directly to a single document in the collection.

  • Lets create schema in codes:

import mongoose from "mongoose"

const CarsSchema = mongoose.Schema({
    Name: String,
    Model: String,
    Price: String,
    meta: {
        Fuel_Type: String,
        Mileage: String,
        Seating_Capacity: Number
    },
})

export default mongoose.model("Cars",CarsSchema)
  • Now in Server.js write some get and post request.

  • For Get request:

app.get("/Cars", function (req, res) {

    try {
        Cars.find((err, data) => {
        if (err) {
            res.status(500).send(err)
        }
        else {
            res.status(200).send(data)
        }
    })
    } catch (error) {
        console.log(error);
    }
})
  • Here Cars.find() will retrieve data from database.

  • For Post request:

app.post("/Cars_add", function (req, res) {

    const dbfeed = req.body
    try {
        Cars.create(dbfeed, (err, data) => {
        if (err) {
            res.status(500).send(err)
        }
        else {
            res.status(201).send(data)
        }
    })
    } catch (error) {
        console.log(error);
    }
})
  • Here Cars.create() will push the data to database in the form of json.

  • Now lets combine all the code:

import express from 'express'
import mongoose from "mongoose"
import Cors from 'cors'
import Cars from './Cars'

var app = express()
var port = process.env.PORT || 8080 

app.use(express.json())
app.use(Cors())

var Connection_url = 'mongodb+srv://Rest-API_lmas:<password>@cluster0.gklyj.mongodb.net/<dbname>?retryWrites=true&w=majority'

mongoose.connect(Connection_url, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
})


app.get("/", function (req, res){
    res.send( "Welcome to Tutorial of REST API using MongoDB, ExpressJS and NodeJS");
})

app.get("/Cars", function (req, res) {

    try {
        Cars.find((err, data) => {
        if (err) {
            res.status(500).send(err)
        }
        else {
            res.status(200).send(data)
        }
    })
    } catch (error) {
        console.log(error);
    }
})

app.post("/Cars_add", function (req, res) {

    const dbfeed = req.body
    try {
        Cars.create(dbfeed, (err, data) => {
        if (err) {
            res.status(500).send(err)
        }
        else {
            res.status(201).send(data)
        }
    })
    } catch (error) {
        console.log(error);
    }
})



app.listen(port)
  • Now run the server by using nodemon
nodemon server.js
  • Open the browser and openlocalhost:8080 you will see the default text and when you openlocalhost:8080/Cars you will see a empty list with no data in it.

Let try it using Postman…

  • Now lets try to post the data to it using postman and json data is:.

[
    {
        "name": "Kia Sonet",
        "Model": "Sonet",
        "Price": "Rs. 6.79 - 13.19 Lakh",
        "meta":{
            "Fuel_Type": "Petrol / diesel",
            "Mileage":"18.4 - 24.1 Kmpl",
            "Seating_Capacity": 5
        }
    }
]
  • Now lets try to get the data from the server:

Great you have completed the REST API using MongoDB , NodeJs and ExpressJs

Now Lets try to host the application in “HEROKU”

  • Now open the heroku application and if you don’t have an account create or just login.

  • Now on top left click on New button you will see two options 1. Create new app, 2. Create new pipeline. Click on Create New app, it will ask you to enter the app-name with there conditions and click Create-app button.

  • Open command prompt and navigate to your project folder.

  • Initializing the empty git using git init and follow the steps from heroku website. Create a .gitignore file add this:

You can also find the project in REST_API-MongoDB repository.

Thanks for reading……