How to Delete MongoDB Data Using Mongoose and Node.js Expresss

Delete MongoDB Data Using Mongoose: In this tutorial, you will learn to Delete MongoDB data with a great example. This example will give you the best deleting concept in Node.js Express. Even you will get a free script to implement in your project.

This tutorial is shared the delete script with  Express MVC pattern. This means all the script is written with a separate Model, View & controller file that will be very simple to understand. So, You will easily learn How to Delete MongoDB data Using Mongoose Node.js Express.

Delete MongoDB Data using mongoose

 

Delete  MongoDB Using Mongoose

Mongoose query is the best solution to delete MongoDB data. So, You should use it for writing the deleting query.

Before getting started, you will have to configure the following required things to execute Node.js Express on your computer.

Now, I’m going to explain this tutorial through the following steps:-

Basic Configuration

First of all, You must configure the following things:-

  •  Install Node.js or Express Application. You can learn it through the following URL

How to Install Express Application

  • After Installing Express Application, Create MVC Pattern as the following structure.
myapp/
  |__bin/
  |__config/
  |     |__database.js
  |__controllers/
  |     |__user-controller.js
  |__models/
  |     |__user-models.js
  |__node_modules/
  |__public/
  |__routes/
  |     |__user-route.js
  |__views/
  |     |__edit-user-form.ejs
  |     |__user-data-list.ejs
  |     |__user-form.ejs    
  |__package-lock.json
  |__package.json

 

  • You must connect MongoDB to Node.js using mongoose. you can learn it through the following URL.

Connect MongoDB with Node.js Using Mongoose

You can use the following mongoose script in Express to connect MongoDB to Node.js

File Path: config/database.php

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;
  • First, You should Insert & Fetch MongoDB Data. If you don’t know, you can learn  through the following URL

 Insert Data Into MongoDB Using Mongoose and Express

 Fetch Data From MongoDB Using Mongoose and Express

Model – Write Mongoose Query to Delete MongoDB Data

Now, do the following things to create a model for fetching  data from MongoDB

Load the mongoose module

var mongoose=require('mongoose');

Load the database module

var db = require('../config/database');

Create a schema with the same name as input fields name

// create an schema
var userSchema = new mongoose.Schema({
            fullName: String,
            emailAddress:String,
            city:String,
            country:String
        });

userTable=mongoose.model('users',userSchema);

Write the following script to delete MongoDB data.

deleteData:function(deleteId, callback){
                  
      userData= userTable.findByIdAndDelete(deleteId);
      userData.exec(function(err, data){
        if (err) throw err;
         return callback(data);
      })
}

Complete Script

File path: models/user-model.js

var mongoose=require('mongoose');
var db = require('../config/database');

// create an schema
var userSchema = new mongoose.Schema({
            fullName: String,
            emailAddress:String,
            city:String,
            country:String
        });

userTable=mongoose.model('users',userSchema);
        
module.exports={

   deleteData:function(deleteId, callback){
                  
      userData= userTable.findByIdAndDelete(deleteId);
      userData.exec(function(err, data){
        if (err) throw err;
         return callback(data);
      })
   }
}
    

 

 

Controller – Load Model to execute Delete Query

Load the following  user-model.js in the controller

var userModel= require('../models/user-model');

Write the following script to  execute delete Query

deleteData:function(req, res){
      
      var deleteId= req.params.id;
      userModel.deleteData(deleteId,function(data){
         res.redirect('/user/data-list')
         console.log(data.affectedRows + " record was deleted");
      });
}

 

Complete Script:

File Path: controllers/user-controller.js

var userModel= require('../models/user-model');
module.exports={

    deleteData:function(req, res){
      
      var deleteId= req.params.id;
      userModel.deleteData(deleteId,function(data){
         res.redirect('/user/data-list')
         console.log(data.affectedRows + " record was deleted");
      });
    }

}

View – Write HTML Code to Create Edit Form

You have to delete data on the bass of its id. So, You can delete each data from the user-data-list.ejs by clicking the delete button

Route – Create & Load Route to Update Data

Create Route:

Load  user-controller.js  using the following script

var userController= require('../controllers/user-controller');

You need to create the following route of the data list. this route was taught in update MongoDB tutorials.

router.get('/data-list',userController.fetchData);

Create the following route to delete data

router.get('/delete/:id',userController.deleteData);

 

Complete route script:

File Path: routes/user-route

var express = require('express');
var router = express.Router();
var userController= require('../controllers/user-controller');


router.get('/data-list',userController.fetchData);
router.get('/delete/:id',userController.deleteData);
module.exports = router;

 

Load Route:

load user-route.js in the app.js

var userRouter = require('./routes/user-route');
app.use('/user', userRouter);

You have to enter the following URL to delete MongoDB data using Mongoose

http://localhost:3000/user/data-list

 

Suggestion:

Dear developers, I hope you have understood the above script, Now you are able to delete  MongoDB Data using Mongoose and Node.js express

I will share more tutorials on Node.js/Express asap. If you have any doubts or questions. Kindly ask me through the below comment box.

Leave a Comment