NodeJS MongoDB Remove by Id with Mongoose

Introduction

Delete is one of the CRUD operations in MongoDB. Using mongoose with NodeJS and MongoDB provides many methods to remove data from a collection. One of these methods in removeById. It is a simple function that is used to remove a document from a collection using the value of the _id field. This as you can imagine is a commonly used command and is a good one to have memorized if you’re working with Mongoose frequently. We’ll go over a demonstration using the command in the hopes that you can apply some of the code to your problem at hand.

Prerequisites

  • You should have a basic level of understanding of NodeJS, MongoDB, Mongoose, and how all these technologies interact to follow this tutorial.
  • You should understand npm ( node package manager) and how to install packages.
  • You should have a basic understanding of what middleware does.

removeById function in Mongoose

As the name suggests the removeById method removes a document from a collection. All we have to do is pass the function the id of that document. Let’s understand how can we use the removeById in mongoose.

First of all, we need an instance of express.

var app = express();

Usually, when a document needs to be removed by id, the id is passed through the params. We will do exactly this our example. But to access the body of the request, we need a middleware. We will use body-parser middleware.

To install the body-parser middleware, use the following commands.

npm install body-parser@1.0.2 --save

After installing the body-parser middleware, we can use it in our express file.

app.use(bodyParser());

But before these, we need to define the dependencies at the top of our express file.

var express = require("express");

bodyParser = require("body-parser");

We can use another middleware, app.param.

app.param("collectionName", function(req, res, next, collectionName) {
  req.collection = db.collection(collectionName);
  return next();
});

This middleware defines, that whenever the given pattern is present in the URL, we select a particular collection. Then, we save that collection as a property of the request object.

Now we can use the removeById method.

app.del("/collections/:collectionName/:id", function(req, res, next) {
  req.collection.removeById(req.params.id, function(err, output) {
    if (err) {
      return next(err);
    }
    res.send(output === 1 ? { msg: "success" } : { msg: "error" });
  });
});

Whenever a URL, starting with ‘collections’, then followed by a collection name and id of a document, the above function will be triggered. Then we used req.collection to invoke the removeById method. The removeById method has two parameters – req.params.id and a callback function.

Th req.params.id method contains the id of the document that was passed along the URL.

The callback function also has two parameters – err and output. In the body, first, we check if there is an error using the if statement. If there is no error, we check the value of output. If output equals 1, the operation was success else it failed.

Conclusion

We have showed you briefly how to set up an express app that is able to use the Mongoose removeById function that includes error handling. We hope you can apply the snippets you’ve seen here to your application.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.