How to Remove Documents using Node.js Mongoose?
Last Updated :
15 Apr, 2024
When working with Node.js and MongoDB, managing data involves removing documents from collections. In this article, we will explore how to remove documents using Node.js and Mongoose, a popular MongoDB library that simplifies database interactions. We'll cover the various methods provided by Mongoose for removing documents including removing a single document, removing multiple documents, and removing all documents from a collection.
How to Remove Documents Using Node.js Mongoose?
When working with Node.js and Mongoose, removing documents involves interacting with a MongoDB collection and executing delete operations based on certain conditions. Mongoose simplifies this process by providing methods that abstract away the complexities of MongoDB queries. Below are the methods used in How to remove documents using Node.js Mongoose as follows:
- findOneAndDelete(): This method deletes a single document that matches the specified conditions and returns the deleted document.
- deleteMany(): Use this method to delete multiple documents that match the specified criteria.
- deleteMany(): To remove all documents from a MongoDB collection, you can use the deleteMany() method with an empty query {}. This effectively deletes all documents in the specified collection.
Setting Up Mongoose
To begin, let's set up a basic Node.js application that connects to a MongoDB database using Mongoose.
1. Create a Node.js Project
Initialize a new Node.js project and install Mongoose as shown above.
2. Create a Connection to MongoDB
const mongoose = require("mongoose");
const url = 'mongodb+srv://Abdullah:[email protected]/node?retryWrites=true&w=majority'
mongoose.connect(url)
.then((result) => {
console.log('connected to Mongodb');
}).catch((err) => {
console.error(err);
});
module.exports = mongoose;
Note:Replace 'mongodb://localhost:27017/mydatabase' with the connection URL to your MongoDB database.
Defining a Mongoose Schema and Model
Next, define a Mongoose schema and model to interact with a specific MongoDB collection.

Let's set up an Environment:
To understand How to remove documents using Node.js Mongoose we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called books which contains information shown in below images.

To remove a document, we typically perform a findOneAndDelete or deleteOne operation on the model.
1. Removing a Single Document
The findOneAndDelete() method is used to delete a single document that matches a given condition. It accepts a filter object to specify which document to delete and returns the deleted document in the callback.
Here's a basic example:
Book.findOneAndDelete({ title: 'The Catcher in the Rye' }, (err, result) => {
if (err) {
console.log(err);
} else {
console.log('Successfully deleted:', result);
}
});
Output:

2. Removing Multiple Documents
The deleteMany() method is used to remove multiple documents that satisfy certain conditions. It also takes a filter object to specify the criteria for deletion. Here's how you might use it:
// Remove all books published before 2000
return Book.deleteMany({ year: { $lt: 2000 } });
})
.then((deleteManyResult) => {
console.log('Successfully deleted:', deleteManyResult.deletedCount, 'documents');
mongoose.connection.close(); // Close the connection after deletion operations
})
.catch((err) => {
console.log('Error:', err);
mongoose.connection.close(); // Close the connection on error
});
output:

3. Removing All Documents
To remove all documents from a MongoDB collection, we can use the deleteMany() method with an empty query {}. This effectively deletes all documents in the specified collection.
Book.deleteMany({})
.then((deleteManyResult) => {
console.log('Successfully deleted:', deleteManyResult.deletedCount, 'documents');
})
.catch((err) => {
console.log('Error:', err);
});
Output:

Conclusion
Overall, we have learned how to remove documents from MongoDB collections using Node.js and Mongoose. We explored the findOneAndDelete() method for deleting a single document, the deleteMany() method for removing multiple documents, and how to remove all documents from a collection using deleteMany() with an empty query. These methods provide flexibility and control when managing data in MongoDB, making them valuable tools for Node.js developers working with MongoDB databases.
Similar Reads
How to replace one document in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Insta
1 min read
How to find all the document keys of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
1 min read
How to Get Data from MongoDB using Node.js?
One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to get Distinct Documents from MongoDB using Node.js ?
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. MongoDB module: This module of Node.js is used for connecting the MongoD
2 min read
How to drop database of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to Retrieve Data from MongoDB Using NodeJS?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
3 min read
How to Create Relationships with Mongoose and Node.JS?
Mongoose is a powerful ODM (Object Data Modeling) library for MongoDB and Node.js, allowing developers to define schemas and interact with MongoDB using models. Creating relationships between schemas is important for building complex applications with interrelated data. This article will guide you t
5 min read
Mongoose Documents Updating Using save()
An important aspect of a mongoose model is to save the document explicitly when changes have been made to it. This is done using the save() method. In this article, we will see its uses and see the things we should keep in mind while saving our document. We will take the help of an example to unders
6 min read
How to Connect to a MongoDB Database Using Node.js
MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
4 min read