Node JS Express MongoDB REST API Tutorial

Node JS Express MongoDB REST API Tutorial

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');
    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 {

router.get('/:id', function(req, res){
    console.log('getting one book');
    }).exec(function(err, book){
        if(err) {
            res.send('error has occured');
        } else {
});'/', function(req, res){
    var newBook = new Book();
    newBook.title = req.body.title; =;
    newBook.category = req.body.category;, book){
        if(err) {
            res.send('error saving book');
        } else {

router.put('/:id', function(req, res){
        $set: {
            title: req.body.title,
            category: req.body.category
        upsert: true
    },function(err, newBook){
        if(err) {
            res.send('error updating book');
        } else {

router.delete('/:id', function(req, res){
    },function(err, book){
        if(err) {
            res.send('error deleting book');
        } else {

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();



    extended: true



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";
      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


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.

Recommended Node JS Tutorials


My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to Node JS Express MongoDB REST API Tutorial

  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *