15-Nov-2022
.
Admin
Hello Friends,
I will explain step-by-step tutorial node js express MongoDB rest API tutorial. I would like to show you building a rest API with express. I would like to show you the node. Here you will learn MongoDB. you will do the following things for how to build a restful API using node.
For example, a REST API would use a GET request to retrieve a record, a POST request to create one, a PUT request to update a record, and a DELETE request to delete one. All HTTP methods can be used in API calls. A well-designed REST API is similar to a website running in a web browser with built-in HTTP functionality.
This tutorial will create book crud rest API with MongoDB in the node js express app using the mongoose module.
Step 1: Create Node Express js App
Execute the following command on the terminal to create the node js app:
mkdir my-app
cd my-app
npm init -y
Step 2: Install express flash Validator ejs body-parser mongoose Modules
Execute the following command on the terminal to express flash ejs body-parser MySQL dependencies :
npm install -g express-generator
npx express --view=ejs
npm install
npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install cors --save
npm install mongoose
body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and makes it available under req.body property. In other words, it simplifies incoming requests.
Express-Flash – Flash Messages for your Express Application. Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
Express-Session– Express-session – an HTTP server-side framework used to create and manage a session middleware.
Express-EJS– EJS is a simple templating language which is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages
Mongoose – Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.
Step 3: Connect App to MongoDB
Create a database.js file in your app root directory and add the following code into it to connect your app to the MongoDB database:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});
var conn = mongoose.connection;
conn.on('connected', function() {
console.log('database is connected successfully');
});
conn.on('disconnected',function(){
console.log('database is disconnected successfully');
})
conn.on('error', console.error.bind(console, 'connection error:'));
module.exports = conn;
Step 4: Create Model
Create Models directory and inside this directory create userModel.js file; Then add following code into it:
var db = require("../database");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: String,
author: String,
category: String
});
module.exports = mongoose.model('Book', BookSchema);
Step 5: Create CRUD Apis Routes
Create fetch insert update, delete restful API routes from MongoDB in node js; so visit routes directory and open users.js route file; Then add the following insert update, delete in node js MongoDB routes into it:
var express = require('express');
var Book = require('../models/book');
var router = express.Router();
router.get('/', function(req, res){
console.log('getting all books');
Book.find({}).exec(function(err, books){
if(err) {
res.send('error has occured');
} else {
console.log(books);
res.json(books);
}
});
});
router.get('/:id', function(req, res){
console.log('getting one book');
Book.findOne({
_id: req.params.id
}).exec(function(err, book){
if(err) {
res.send('error has occured');
} else {
console.log(book);
res.json(book);
}
});
});
router.post('/', function(req, res){
var newBook = new Book();
newBook.title = req.body.title;
newBook.author = req.body.author;
newBook.category = req.body.category;
newBook.save(function(err, book){
if(err) {
res.send('error saving book');
} else {
console.log(book);
res.send(book);
}
});
});
router.put('/:id', function(req, res){
Book.findOneAndUpdate({
_id: req.params.id
},{
$set: {
title: req.body.title,
author: req.body.author,
category: req.body.category
}
},{
upsert: true
},function(err, newBook){
if(err) {
res.send('error updating book');
} else {
console.log(newBook);
res.send(newBook);
}
});
});
router.delete('/:id', function(req, res){
Book.findByIdAndRemove({
_id: req.params.id
},function(err, book){
if(err) {
res.send('error deleting book');
} else {
console.log(book);
res.send(book);
}
});
});
module.exports = router;
Step 6: Import Modules in App.js
Import express flash session body-parser mongoose dependencies in app.js; as shown below:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const books = require('./routes/books');
const app = express();
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(cors());
app.use('/books', books);
// Handling Errors
app.use((err, req, res, next) => {
// console.log(err);
err.statusCode = err.statusCode || 500;
err.message = err.message || "Internal Server Error";
res.status(err.statusCode).json({
message: err.message,
});
});
app.listen(3000,() => console.log('Server is running on port 3000'));
Step 7: Start App Server
You can use the following command to start the node js app server:
//run the below command
npm start
after run this command open your browser and hit
http://127.0.0.1:3000/books
I hope it can help you...
#Node.js Express
#Node JS