Node js + MongoDB + REST API Example

Node.js express + mongodb crud rest api; Through this tutorial, i am going to show you how to create crud rest api using node.js express + mongodb with mongoose.

Build a REST API with Node + Express and MongoDB

Use the following steps to build rest ful crud api with node.js express and mongodb:

  • 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

Run 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

Run 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

Leave a Comment