DEV Community


What is mongoDB and how to get started.

・3 min read

In this article I will share how to build Restful API with Nodejs Express MongoDB

In order to develop and run this restful API, we need Node.js, which is JavaScript runtime installed on our machine. With Node.js comes NPM which is a node package manager that we will use to install other packages like Express needed to develop this API.
Also, we need to have MongoDB installed on the machine.

MongoDB Installation/Setup
MongoDb is a no-SQL database that stores data in the form of JSON object which is called Document. All Documents are stored in the container called Collection. So first Collection is created and then Document in inserted into it.

Get Started…
Start with creating project folder.

$ mkdir webapi

$ cd webapi

Now we will start with creating package.json file which is the first building block for Node.js application and holds application configuration and package dependencies details that is required in order to run the application.

$ npm init --yes

Install Express, Mongoose and body-parser

Mongoose is a MondoDB object data modelling package that provides a straight-forward, schema-based solution to model data in the Node.js application.
body-paser is Node.js middleware for parsing incoming request bodies in a middleware before request handlers and is available under the req.body property.

So install all these packages by running following command in the command window.

$ npm i express mongoose body-parser –save

–save option will add entry for these packages in the dependencies section in package.json file for our project.

Write Code…
Now open the code editor to start writing code.

Create db.js file and add following code to create and export connection with MongoDB using mongoose.

const mongoose = require("mongoose");
{ useNewUrlParser: true, useUnifiedTopology: true },
err => {
if (!err) console.log("Successfully connect to MondoDB...");
"Connection to MongoDb failed :" + JSON
.stringify(err, undefined, 2)

module.exports = mongoose;

Create index.js file and add following code to create Express server to host our restful API. It will also import mongodb connection from db.js.
const bodyParser = require("body-parser");
const { mongoose } = require("./db");
const customer = require("./Controller/CustomerController");

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

//added middleware code
app.use("/customers", customer);

const port = process.env.port || 3000;
app.listen(port, () => {
console.log(server listening at port :${port});
Now we need to create object data model to store Customer data in the MongoDB database. So create schema folder and create Customer.js file in it. Add following code to hold Customer model schema and export it as well.
const mongoose = require("mongoose");

var Customer = mongoose.model("Customer", {
first_name: String,
last_name: String,
gender: String,
age: Number,
email: String

module.exports = { Customer };
The last piece of code is to add controller code that will expose our restful API endpoints. So create Controller folder and in it create CustomerController.js file.

Now add following code for CRUD operations.

Add following code to handle GET request to fetch the Customers.
router.get("/", (req, resp) => {
Customer.find((err, docs) => {
if (err)
"Error while getting customers..." + JSON
.stringify(err, undefined, 2)
else resp.send(docs);

To create new Customer, add following code to handle POST request from the client."/", (req, resp) => {
let cust = new Customer({
first_name: req.body.first_name,
last_name: req.body.last_name,
gender: req.body.gender,
age: req.body.age,
});, doc) => {
if (err)
"error in saving customers..." + JSON
.stringify(err, undefined, 2)
else resp.send(doc);

Launch the API
Now run following command to host our restful API.

$ node index.js

It will launch the web server that will host our API available at http://localhost:3000/Customers

Test the API
Now open the Postman Web API Client application and click on the Create a request to initiate an API request to our restful API.

Take following steps to test POST request handler to create the Customer.

Select POST HTTP verb from the drop down.
Enter request URL http://localhost:3000/Customers for post request.
Select Body tab and then select raw radio button and finally select type JSON from the drop down.
In the request body enter following JSON object representing our Customer resource that we want to create.
"first_name" : "Amit",
"last_name" : "Patil",
"gender" : "Male",
"age" : 39,
"email" : ""

Discussion (0)