Node Express Delete Data By Id from MongoDB Tutorial

In this extensive guide, we will help you learn how to delete data object from the MongoDB collection in the Node js app.

You will ascertain how to set up a MongoDB connection in Node js and how to build a node app from scratch.

To connect the node app to MongoDB, we will use the Mongoose module. Also, You will be taught how to fetch records from the Mongo database and display them in the Node app using the Bootstrap package.

Deleting the data from MongoDB IN Node requires a Node app. You will be shown everything in detail. For instance, we will cover node app setting, routes creation for API building, MongoDB connection using Mongoose, and node server configuration.

How to Remove or Delete Data by Id from MongoDB (Mongoose) Database in Node Js

  • Step 1: Create Directory
  • Step 2: Install Required Modules
  • Step 3: Connect MongoDB Connection
  • Step 4: Create Schema
  • Step 5: Build Routes
  • Step 6: Update App Js File
  • Step 7: Delete MongoDB Record in Node
  • Step 8: Run Node Server

Create Directory

Head over to the terminal and use the command to generate new folder.

mkdir node-moon

Step into the project folder:

cd node-moon

Install Required Modules

We need a boilerplate for node project, where we can create models, views and compile the code to work properly. Hence, we are installing express and EJS modules.

npx express --view=ejs

Let us install few more packages:

npm install -g express-generator

npm install

npm install mongoose express-flash express-session body-parser

Connect MongoDB Connection

You now need to make the db.js, in this file we are going to keep database connection configuration.

Do not forget to add the given code into the db.js file.

var mongoose = require('mongoose')
mongoose.connect('mongodb://0.0.0.0:27017/nodedemodb', {
  useNewUrlParser: true,
})
var conn = mongoose.connection
conn.on('connected', function () {
  console.log('Database successfully connected')
})
conn.on('disconnected', function () {
  console.log('Database disconnected ')
})
conn.on('error', console.error.bind(console))
module.exports = conn

Create Schema

We need a data object prototype (schema), hence we need to create the models folder and UserModel.js file into it.

Make sure to insert the given code into the models/UserModel.js file.

const mongoose = require('mongoose')
const Schema = mongoose.Schema
var db = require('../db')

let userSchema = new Schema(
  {
    name: {
      type: String,
    },
    email: {
      type: String,
    },
  },
  {
    collection: 'nodedemodb',
  },
)

module.exports = mongoose.model('Users', userSchema)

Build Routes

Routes allow you to form APIs, we need two apis for making requests to server for fetching and deleting the data by id from mongoDb.

Into the routes/users.js file add the given code for forming routes.

var express = require('express')
var router = express.Router()

var UserModel = require('../models/UserModel')

/* GET Users list. */
router.get('/users', function (req, res, next) {
  UserModel.find((err, docs) => {
    if (!err) {
      res.render('index', {
        data: docs,
      })
    } else {
      console.log('Users not found: ' + err)
    }
  })
})

// DELETE User
router.get('/delete/(:id)', function (req, res, next) {
  UserModel.findByIdAndRemove(req.params.id, (err, doc) => {
    if (!err) {
      res.redirect('/users')
    } else {
      console.log('User can not be deleted: ' + err)
    }
  })
})

module.exports = router

Update App Js File

The ejs package by default created the app.js file, already imported essential modules, packages and database connection. However we just have to import the body parser, and routes module.

Go ahead copy the entire given code into the app.js file.

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 routeUser = require('./routes/users')

var app = express()

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use(
  session({
    secret: 'abeb13212',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 },
  }),
)

app.use(flash())
app.use('/', routeUser)

app.use(function (req, res, next) {
  next(createError(404))
})

app.use(function (err, req, res, next) {
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}
  res.status(err.status || 500)
  res.render('error')
})

app.listen(4000, function () {
  console.log('App working on: 4000')
})

module.exports = app

Delete MongoDB Record in Node

We have to set up the view; in this view, we will use the Bootstrap table component to display the data in tabular form, where we have to add the delete button to remove the MongoDB delete data by id.

Open the views/index.ejs file and place the following code into the file.

<!DOCTYPE html>
<html>
  <head>
    <title>Node Remove Data from MongoDB Tutorial</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="/stylesheets/style.css" />
  </head>
  <body>
    <h2 class="mb-3">Node Delete Records from MongoDB Example</h2>

    <table class="table mt-3">
      <thead>
        <tr>
          <th scope="col">#ID</th>
          <th scope="col">Name</th>
          <th scope="col">Email</th>
        </tr>
      </thead>
      <tbody>
        <% if(data.length){ for(var i = 0; i < data.length; i++) {%>
        <tr>
          <th scope="row"><%= (i+1) %></th>
          <td><%= data[i].name%></td>
          <td><%= data[i].email%></td>
          <td>
            <a class="btn btn-danger" href="/delete/<%= data[i]._id%>"
              >Delete</a
            >
          </td>
        </tr>
        <% } }else{ %>
        <tr>
          <td colspan="3">Record not found</td>
        </tr>
        <% } %>
      </tbody>
    </table>
  </body>
</html>

Run Node Server

Run the given command from the terminal to run the node app.

npm start

Open the browser, type the given url to view the app and remove the mongoDB data by using the id.

http://127.0.0.1:4000/users

Node Express Delete Data By Id from MongoDB Tutorial

Summary

In this comprehensive and step-by-step guide, we have taught how to delete data by ID from the MongoDB database in the Node environment.

Moreover, we have learned how to create APIs using Express js and showed you how delete by id work in Node in conjunction with Mongoose schema.