Create a restful crud APIs with node.js express and MongoDB; This tutorial will show you how to build/create a crud rest API using node.js express and MongoDB with mongoose.
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 node js express app using mongoose module.
Build a Restful CRUD Apis with Node.js Express + Mongodb
Follow the below-given instruction to create crud rest api using node.js express and mongodb with mongoose:
- Step 1 – Create Node Express js App
- Step 2 – Install express Validator flash ejs body-parser mongoose dependencies
- Step 3 – Connect App to MongoDB
- Step 4 – Create Model
- Step 5 – Create CRUD Apis Routes
- Step 6 – Import Modules in App.js
- Step 7 – Start App Server
Step 1 – Create Node Express js App
Execute the following command on terminal to create 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 make it available under req.body property. In other words, it simplifies the incoming request.
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 database.js file into 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 5 – 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 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
Conclusion
Build restful crud api with node.js express and mongodb; In this tutorial; you have learned how to build/create a crud rest api using node.js express and mongodb with mongoose.
Brilliant article! I don’t see such articles any more these days. Well thought out and really well written. Couldn’t agree any further. Thank you for this.