Building a Simple Restful Web Service Using ExpreeJS, Mongoose, Body-Parser and MongoDB

Kawee Lokuge
4 min readJun 19, 2018

Prerequisites

NodeJS is installed in the PC.

MongoDB is installed and running.

Setting Up

Go to the Folder that you are going to create the project.

Open CMD(Windows)/Terminal(Linux/MAC) inside the folder and give the command npm init.

Give a name for the Application E.g. — first-app

Keep the other properties as default and at the end type yes and hit enter.

Type the following commands to download the required dependencies.

npm install express --savenpm install mongoose --savenpm install body-parser --save

Note — save is for adding the dependencies to the package.json file.

Overview

We are going to write a simple application to add, delete, update and get a user.

Let’s Start Coding!

Defining the Server

Create a JavaScript file called app. Here we are going to code the express server and add the dependencies to our application. The server runs on port 8083. For now forget about the following two lines:

const Routes = require('./Routes');
app.use('/',Routes);

We will talk about these two lines later.

BodyParser is used to accept JSON objects.

//root fileconst Express = require('express');const app = Express();
const BodyParser = require("body-parser");
const Routes = require('./Routes');
app.use(BodyParser.json());
app.use('/',Routes);
app.listen(8083,'localhost',function (err) {
if(err){
console.log(err);
process.exit(-1);
}
console.log('Server listens port 8083');
});

Defining the Schema

First create a folder called DBSchema. Inside the folder create a JavaScript file called DBConfig. In this file let’s create the Schema for user. The user have 3 properties: name, address, and password.

var mongoose = require('mongoose');const Schema = mongoose.Schema;const UserSchema = new Schema({
name: {
type: String,
require: true
},
address:{
type: String,
require: false
},
password:{
type: String,
require: true
}
});mongoose.model('User',UserSchema);mongoose.connect('mongodb://127.0.0.1:27017/userdb',function (err) {
if(err){
console.log(err);
process.exit(-1);
}
console.log('connected to DB');
});module.exports = mongoose;

After creating the UserSchema, We create a model from it. You can give any name to the model. Above the model is named User. Then the connection to the monogo DB is coded. Userdb is the database name that will be created. Finally we export the mongoose object.

Defining Controllers

Create a folder called UserController. In the folder create a JS file called Controller. Here we are coding all the functions to insert, update, delete, and get users. To begin with we import the mongoose object and assign it to constant variable called UserSchema.

Using this UserSchema object we get, add, update and delete users from the database.

const mongoose = require("../DBSchema/DBConfig");const UserSchema = mongoose.model('User');const Controller = function () {this.insertUser = function (data) {
return new Promise(function (resolve, reject) {
var User = new UserSchema({
name: data.name,
address: data.address,
password: data.password
});
User.save().then(function () {
resolve({status: 200, message:"User inserted Successfully"});
}).catch(function (err) {
reject({status: 500, message:"Error "+err});
});
});
};
this.updateUser = function (id,data) {
return new Promise((resolve, reject) => {
UserSchema.update({_id: id},data).then(()=>{
resolve({status: 200,message: "User updated Successfully"});
}).catch(function (err) {
reject({status: 500, message: err});
})
});
};

this.searchAll = function () {
return new Promise(function (resolve,reject) {
UserSchema.find().exec().then(function (data) {
resolve({status: 200,message: data});
}).catch(function (err) {
reject({status: 500, message: err});
});
});
};
this.search = function (id) {
return new Promise(function (resolve,reject) {
UserSchema.find({_id: id}).exec().then(function (user) {
resolve({status: 200,message: user});
}).catch((err) =>{
reject({status: 500, message: err});
})
});
};
this.delete = function (id) {
return new Promise(function (resolve,reject) {
UserSchema.remove({_id: id}).then(()=>{
resolve({status: 200,message: "User Removed"});
}).catch(err =>{
reject({status: 500, message: err});
});
})
}
};
module.exports = new Controller();

Finally we export the Controller.

Defining Routes

Defining User.Route

Go to the UserController folder you have previously created. Create a new JS file called User.Route. In the User.Route file we are defining and using the router object that is created using Express.Router(). This router object is used to handle the incoming requests. After that the Controller we have exported in the Controller file is imported. Then HTTP methods (GET, POST, PUT, and DELETE) to handle the incoming requests is coded. Here we are using the methods defined in the Controller to interact with the database.

const Express = require('express');
const router = Express.Router();
const Controller = require('./Controller');router.post('/',function (req, res) {
Controller.insertUser(req.body).then(function (data) {
res.status(data.status).send({message: data})
}).catch(function (err) {
res.status(data.status).send({message: err.message})
});
} );
router.put('/:id',function (req,res) {
Controller.updateUser(req.params.id,req.body).then(data =>{
res.status(data.status).send({message: data.message});
}).catch(err =>{
res.status(err.status).send({message: err.message});
});
});router.get('/:id',function (req, res) {
Controller.search(req.params.id).then(data =>{
res.status(data.status).send({message: data.message});
}).catch(err =>{
res.status(err.status).send({message: err.message});
});
});
router.get('/',function (req,res) {
Controller.searchAll().then(data =>{
res.status(data.status).send({data: data.message});
}).catch(err =>{
res.status(err.status).send({message: err.message});
});
});
router.delete('/:id',(req,res) => {
Controller.delete(req.params.id).then(data =>{
res.status(data.status).send({message: data.message});
}).catch(err =>{
res.status(err.status).send({message: err.message});
});
});
module.exports = router;

Finally we export the router object.

Defining Routes

Go to the main project folder first-app. Then create a new JS file called Routes. Here we are going to define all the routes in the application. Since we have only have one route (User Route) we are adding it inside this file. Therefore we have to import UserRoute from User.Route file.

const Express = require('express');const Routes = Express.Router();
const UserRoute = require('./UserController/User.Route');
Routes.use('/users',UserRoute);module.exports = Routes;

Then we are exporting the Routes object. Now let’s go back to the app.js file we initially created. There we added following two lines.

const Routes = require('./Routes');
app.use('/',Routes);

Here we have imported the Routes from Routes.js file. This is done to direct the incoming request to the routes.js file where it will be handled according to the URL.

Running the Application

Add the following line to the package.json file under scripts attribute.

“start”: “node app.js”

Your package.json file should look like the following –

{
"name": "first-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start": "node app.js"
},
"author": "",
"license": "MIT",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.3",
"mongoose": "^5.1.1"
}
}

Finally open the cmd/terminal inside the project directory and issue the command npm start

--

--