\

Part 3 : MEAN APP – RestAPI With MongoDB And NodeJS

RestAPI With MongoDB And NodeJS

In this tutorial, we will see how to build RestAPI With MongoDB And NodeJS. Using MEAN stack we will build API for basic operations such as GET, POST, PUT, DELETE.


Check out the Demo on MEAN Stack Application-BookStore .





Download Bookstore MEAN Application.






Directory

Directory Structure

|  ////////// SERVER SIDE ////////// 
|---Package.json
|
|---node_modules(folder)
|                 |---*files // Dependencies Files
|
|---app.js // main file
|
|---models(folder)
|                 |---book.js // For API

As you can see we have covered the last part in making the package.json file and therefore it automatically creates the node _module folder. Now we will cover the part of making RESTapi.

 

 

Main App

So let’s start with our main app, just to remind that we will be working on backend side in this tutorial part.
Begin with building the main file i.e app.js.

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

app.use(express.static(__dirname+'/client')); // uses the Client folder
app.use(bodyParser.json());

......

app.listen(3000);
console.log('Running on port 3000...');

Now the next part will be doing is creating the directory named as a module which provides the queries.
But in the main app, we will send a request through it. So the first thing we do is to require the module directory and then will create the API methods.

app.js

...
// Connect to Mongoose
mongoose.connect('mongodb://localhost/bookstore');
var db = mongoose.connection;


// On Home Page Get All The Books
app.get('/api/books', (req, res) => {
	Book.getBooks((err, books) => {
		if(err){
			throw err;
		}
		res.json(books);
	});
});
// On Book Details Page Get The Book details
app.get('/api/books/:_id', (req, res) => {
	Book.getBookById(req.params._id, (err, book) => {
		if(err){
			throw err;
		}
		res.json(book);
	});
});
// Adds The New Book To Database
app.post('/api/books', (req, res) => {
	var book = req.body;
	Book.addBook(book, (err, book) => {
		if(err){
			throw err;
		}
		res.json(book);
	});
});
// Update the book with provided ID
app.put('/api/books/:_id', (req, res) => {
	var id = req.params._id;
	var book = req.body;
	Book.updateBook(id, book, {}, (err, book) => {
		if(err){
			throw err;
		}
		res.json(book);
	});
});
// Removes The Book Details From Database
app.delete('/api/books/:_id', (req, res) => {
	var id = req.params._id;
	Book.removeBook(id, (err, book) => {
		if(err){
			throw err;
		}
		res.json(book);
	});
});
...

Models

The Next part will be doing is to do interaction with database i.e. providing queries for RestAPI.

Set Schema

So now create a models path in that create a book.js file.

models/book.js

var mongoose = require('mongoose');

// Book Schema
var bookSchema = mongoose.Schema({
			title:      { type: String, required: true },
			genre:      { type: String, required: true },
			description:{ type: String, required: true },
			author:     { type: String, required: true },
			publisher:  { type: String, required: true },
			pages:      { type: String, required: true },
			image_url:  { type: String, required: true },
			buy_url:    { type: String, required: true },
			create_date:{ type: Date, default: Date.now}
	});
    ..... 

 

Queries

We will create the queries for our application and for working of the RestAPI. We will use the four basic methods i.e GET, POST, PUT, DELETE for an application.

models/book.js

....

var Book = module.exports = mongoose.model('Book', bookSchema);// export model

// Get Books
module.exports.getBooks = (callback, limit) => {
	Book.find(callback).limit(limit);
}
// Get Book
module.exports.getBookById = (id, callback) => {
	Book.findById(id, callback);
}
// Add Book
module.exports.addBook = (book, callback) => {
	Book.create(book, callback);
}
// Update Book
module.exports.updateBook = (id, book, options, callback) => {
	var query = {_id: id};
	var update = {
		title: book.title,
		genre: book.genre,
		description: book.description,
		author: book.author,
		publisher: book.publisher,
		pages: book.pages,
		image_url: book.image_url,
		buy_url: book.buy_url
	}
	Book.findOneAndUpdate(query, update, options, callback);
}
// Delete Book
module.exports.removeBook = (id, callback) => {
	var query = {_id: id};
	Book.remove(query, callback);
}

We have used here ES5 arrow function, in that we will be passing the particular id to get, update, delete the book with a perticular ID.

 

API Demo In Postman App
RestAPI With MongoDB And NodeJS

Run The App

After completing the design all you need to run is Node app And the MongoDB server. so just one command in terminal


 $ node app

After that start the MongoDB Server from the command pad. If you dont know just see the Demo Here

MEAN Stack Series – Links

About This Author

Hi This Is Rehmaanali. Blogging Is Just A Hobby. Graduate In Bsc Computer Science

Post A Reply