Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to set the document value type in MongoDB using Node.js?
Next article icon

How to Remove Documents using Node.js Mongoose?

Last Updated : 15 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. findOneAndDelete(): This method deletes a single document that matches the specified conditions and returns the deleted document.
  2. deleteMany(): Use this method to delete multiple documents that match the specified criteria.
  3. 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.

schema

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.

booksColl

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:

Removing-a-Single-Document

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:

Removing-Multiple-Documents

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:

Removing-All-Documents

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.


Next Article
How to set the document value type in MongoDB using Node.js?

A

abdullahaz93z
Improve
Article Tags :
  • 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.  Inst
    1 min read
  • How To Query For Documents In MongoDB Using NodeJS?
    MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
    4 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 Mongo
    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 Connect Node.js To MongoDB Atlas Using Mongoose?
    MongoDB Atlas is a cloud-based database service that offers robust features and scalability for managing our data. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple HTML form. In this tutoria
    6 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences