How to Delete Data From Mongodb Using Node js

Node js delete data from mongoDb database; In this tutorial; i am going to show you how to delete data from mongoDB database using by id in Node js + Express App.

Through this tutorial; you will learn how to delete data from mongoDB + mongoose using by id in node js express app.

Node js + Express + MongoDB Mongoose Delete Data Example

  • Step 1 – Create Node Express js App
  • Step 2 – Install Node Modules
  • Step 3 – Configure MongoDB Connection
  • Step 4 – Create Model
  • Step 5 – Create List and Delete Routes
  • Step 6 – Create Views
    • Create List Page and Delete Button
  • Step 7 – Add Modules in App.js
  • Step 8 – Start App Server

Step 1 – Create Node Express js App

Run the below given command on terminal to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Install express flash ejs body-parser mongoose Modules

Run the below given command on the terminal to install 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 mongoose
npm install express-validator cors --save

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 – Configure MongoDB Connection

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/users', {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:

const mongoose = require("../database");
// create an schema
var userSchema = new mongoose.Schema({
            name: String,
var userModel=mongoose.model('users',userSchema);
module.exports = mongoose.model("Users", userModel);

Step 5 – Create List and Delete Routes

Create routes; so visit routes directory and open users.js route file; Then add the following routes into it:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var userModel = require('../models/userModel');
/* GET home page. */
router.get('/', function(req, res, next) {
    userModel.find((err, docs) => {
        if (!err) {
            res.render("users/list", {
                data: docs
        } else {
            console.log('Failed to retrieve the Users List: ' + err);
router.get('/delete/(:id)', function(req, res, next) {
    userModel.findByIdAndRemove(, (err, doc) => {
        if (!err) {
        } else {
            console.log('Failed to Delete user Details: ' + err);
module.exports = router;

Step 6 – Create Views

Create some views; so visit views directory of your app and create list.ejs into it.

Create List Page and Delete Button

Create html markup for display list from mongodb database; So visit views directory and create list.ejs file inside it. Then add the following code into it:

<!DOCTYPE html>
	<title>node js mongodb delete by _id</title>
	<link rel='stylesheet' href='/stylesheets/style.css' />
	<script src=""></script>
	<script src="" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
	<link href="" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head>
	<div> <a href="/" class="btn btn-primary ml-3">Home</a> </div>
	<!--   <% if (messages.error) { %>
  <p style="color:red"><%- messages.error %></p>
<% } %> -->
	<% if (messages.success) { %>
		<p class="alert alert-success mt-4">
			<%- messages.success %>
		<% } %>
			<table class="table">
						<th scope="col">#</th>
						<th scope="col">Name</th>
						<th scope="col">Email</th>
						<th width="200px">Action</th>
					<% if(data.length){
  for(var i = 0; i< data.length; i++) {%>
							<th scope="row">
								<%= (i+1) %>
								<%= data[i].name%>
								<%= data[i].email%>
							<td> <a class="btn btn-success delete" href="../users/delete/<%= data[i]._id%>">Delete</a> </td>
						<% }
   }else{ %>
								<td colspan="3">No user</td>
							<% } %>

Step 7 – Add Modules in App.js

Import express flash session body-parser mongoose dependencies in app.js; as shown below:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
app.use('/list', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error ='env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
module.exports = app;

Step 8 – 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


Node js mongodb delete by _id using mongoose; In this tutorial, you have learned how to how delete data from mongodb database by _id using mongoose in node js express app.

Recommended Node JS Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.