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://', {
  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 {
router.get('/delete/(:id)', function (req, res, next) {
  UseDataModelrModel.findByIdAndRemove(, (err, doc) => {
    if (!err) {
    } else {
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(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')))
    secret: '123@123acv',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 },
app.use('/', appRoute)
app.use(function (req, res, next) {
app.use(function (err, req, res, next) {
  res.locals.message = err.message
  res.locals.error ='env') === 'development' ? err : {}
  res.status(err.status || 500)
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>
    <title>Node Delete Document with Id from MongoDB Collection Example</title>
    <h2 class="mb-3">Node Delete Records from MongoDB Example</h2>
    <table class="table mt-3">
          <th scope="col">#</th>
          <th scope="col">Name</th>
          <th scope="col">Email</th>
        <% if(data.length){ for(var i = 0; i < data.length; i++) {%>
          <th scope="row"><%= (i+1) %></th>
          <td><%= data[i].name%></td>
          <td><%= data[i].email%></td>
            <a class="btn btn-dark" href="/delete/<%= data[i]._id%>"
        <% } }else{ %>
          <td colspan="3">Record does not exist</td>
        <% } %>

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.

Node Js Delete Document by Id from MongoDB Collection Tutorial


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.


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.