Delete MongoDB Data using Mongoose and Node.js

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 the 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

 

How to Delete MongoDB Data Using Mongoose and Node.js

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

Before getting started, you must –

Insert and Fetch MongoDB Data. Otherwise, you can’t implement the script of this tutorial.

Install Express Application and create the following required folders and files

myapp/
  |__controllers/
  |     |__delete-controller.js
  |__models/
  |     |__delete-model.js
  |__routes/
  |     |__delete-route.js  
  |__database.js
  |

You must connect MongoDB to Node.js using mongoose. So, you use the given script from the following file.

File Name – database.js

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;

 

1. Create a Model to delete data

To create a model, you have to configure the following steps –

  • Include mongoose module and database connection file
  • Create user schema with the name of all input fields
  • Create a method deleteData within module.export to delete data from the database

File Name – delete-model.js

var mongoose=require('mongoose');
var db = require('../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);
      })
   }
}

 

2. Create a controller to delete data

You will have to implement the following steps to create a controller –

  • Include the delete model file
  • Create a method deleteData to delete data by clicking the delete button in the HTML table.

File Name –  delete-controller.js

var deleteModel= require('../models/delete-model');
module.exports={
    deleteData:function(req, res){
      
      var deleteId= req.params.id;
      deleteModel.deleteData(deleteId,function(data){
         res.redirect('/fetch-data')
         console.log(data.affectedRows + " record was deleted");
      });
    }
}

 

3. Create an HTML button with delete Link

You have to create an HTML button with a delete link in the HTML table that code was created in the user-table.ejs. So. open this file and write the following line of code

<td><a href="/delete/<%=data.id%>">Delete</a></td>

4. Create a Route to delete data

  • Include the delete-controller.js
  • Create a route /delete/:id. Where d is a unique number
  • Export the router

File Name – delete-route.js

var express = require('express');
var router = express.Router();
var deleteController= require('../controllers/delete-controller');
router.get('/delete/:id',deleteController.deleteData);
module.exports = router;

5. Load a Route in the app.js

Don’t forget to include use the created route in the app.js.

File Name – app.js

var deleteRouter = require('./routes/delete-route');
app.use('/', deleteRouter);

6. Run Node.js App to delete data

You will have to enter the following URL in the web browser for displaying data with a delete link.

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

After successfully appearing the data in the HTML table, When you click the delete link button then it will redirect to the following URL to delete data from the database

http://localhost:3000/user/delete/id

 

My 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

In this tutorial, I have given you a simple example that is enough to understand the concept of deleting records from the database. Now, you can apply the same concept to easily delete the largest records of data.

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. Even share it with your friends who need it.