Node Js Delete Document by Id from MongoDB Collection Tutorial

Last updated on: by Digamber

In this tutorial, you are going to find out how to remove document from the MongoDB collection using the Node js applicaiton.

To delete the document from MongoDB database we will use the document id that is generated by mongoDB automatically at the time of document creation.

You will learn to create a node app from very basic, we will show you how to use the third-party dependencies in order to make the node app up and running and remove data by MongoDb document Id.

For Node js document delete by id require us to install and use express-flash, mongoose, express-session, body-parser, ejs and express-generator libraries.

How to Remove Record or Document using Id from MongoDB Database in Node Js

  • Step 1: Create Node App
  • Step 2: Add NPM Modules
  • Step 3: Connect to Database
  • Step 4: Build Mongoose Schema
  • Step 5: Create Express Routes
  • Step 6: Create Node Script
  • Step 7: Delete MongoDB Document by Id
  • Step 8: Serve Node Project

Create Node App

Open the command line tool, use the mkdir command to create the new blank folder for node project.

mkdir node-document

Enter in the application folder:

cd node-document

Add NPM Modules

You required certain packages to install that are going to be helping hand for you to build this small feature in node.

npx express --view=ejs
npm install -g express-generator
npm install
npm install express-flash mongoose express-session body-parser

Connect to Database

Create the database.js file, in the node’s root. Then, insert the given code into the file. Make sure to replace your node database name in the file.

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

Build Mongoose Schema

Create the UserModel.js file inside the models/ folder, place the given code into the file to define the schema for database object.

A mongoose schema manifests the prototype of documents within a particular database’s collection.

const mongoose = require('mongoose')
const Schema = mongoose.Schema
let userSchema = new Schema(
  {
    name: {
      type: String,
    },
    email: {
      type: String,
    },
  },
  {
    collection: 'testnode',
  },
)
module.exports = mongoose.model('Users', userSchema)

Create Express Routes

Head over to routes/ folder, also, make the users.js into this directory.

var express = require('express')
var router = express.Router()
var DataModel = require('../models/UserModel')

router.get('/users-list', function (req, res, next) {
  DataModel.find((err, docs) => {
    if (!err) {
      res.render('index', {
        data: docs,
      })
    } else {
      console.log(err)
    }
  })
})
router.get('/delete/(:id)', function (req, res, next) {
  UseDataModelrModel.findByIdAndRemove(req.params.id, (err, doc) => {
    if (!err) {
      res.redirect('/users-list')
    } else {
      console.log(err)
    }
  })
})
module.exports = router

Create Node Script

Get inside the app.js file, here you need to add the packages, routes and other configurations that are going to run the node script.

var createError = require('http-errors')
var path = require('path')
var cookieParser = require('cookie-parser')
var flash = require('express-flash')
var session = require('express-session')
var logger = require('morgan')
var bodyParser = require('body-parser')
var express = require('express')
var appRoute = 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: '123@123acv',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 },
  }),
)
app.use(flash())
app.use('/', appRoute)
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(5555, function () {
  console.log('Node app being served on port: 5555')
})
module.exports = app

Delete MongoDB Document by Id

Ensure that you have opened the views/index.ejs file, add added the suggested code inside the file to formulate the view file that you can test on the browser.

<!DOCTYPE html>
<html>
  <head>
    <title>Node Delete Document with Id from MongoDB Collection Example</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
  </head>
  <body>
    <h2 class="mb-3">Node Delete Records from MongoDB Example</h2>
    <table class="table mt-3">
      <thead>
        <tr>
          <th scope="col">#</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-dark" href="/delete/<%= data[i]._id%>"
              >Remove</a
            >
          </td>
        </tr>
        <% } }else{ %>
        <tr>
          <td colspan="3">Record does not exist</td>
        </tr>
        <% } %>
      </tbody>
    </table>
  </body>
</html>

Serve Node Project

Execute the following command from the cli tool to run the node script.

npm start

Make sure to run the given url to view the app.

http://127.0.0.1:5555/users-list

Node Js Delete Document by Id from MongoDB Collection Tutorial

Conclusion

In this tutorial, you have discovered the step-by-step process on how to delete MongoDB document from MongoDB collection by ID using the node js app.

We also managed to found out how to use mongoose and express js to remove data by id from mongoDB collectiion.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.