Open In App

deleteOne Method in Mongoose

Last Updated : 27 Mar, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

The deleteOne() method in Mongoose is an important tool for performing deletion operations in MongoDB. It allows us to delete a single document from a collection based on a specified condition. In this article, we'll walk you through everything you need to know about the deleteOne() method, including its syntax, installation, usage, and a practical example.

What is Mongoose and Why Use deleteOne()?

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It simplifies working with MongoDB by providing a higher-level abstraction that makes database operations more intuitive. The deleteOne() method is one of the key functions provided by Mongoose for document deletion. Unlike remove(), which can delete multiple documents, the deleteOne() method deletes at most one document that matches the specified condition.

Syntax:

Model.deleteOne(condition, [options], [callback])

Parameters:

  • condition: An object that specifies the filter criteria. Only the first document that matches this condition will be deleted.
  • options (optional): Additional options that can modify the behavior of the deletion. These are not commonly used but can be helpful in specific use cases.
  • callback (optional): A callback function that is invoked once the deletion process is complete. It accepts the result of the deletion operation.

Return:

The deleteOne() method returns a query object that provides information about the deletion process, including whether the operation was successful.

Steps to Install Mongoose Module

Before you can use the deleteOne() method, you need to install the Mongoose package in your Node.js project. Follow these simple steps:

Step 1: Install Mongoose

You can visit the link to Install mongoose module. You can install this package by using this command.

npm install mongoose

Step 2: Verify Installation

After installing mongoose module, you can check your mongoose version in command prompt using the command.

npm version mongoose

Step 3: Setup Your Project

After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.

node index.js

Now that Mongoose is installed and set up, you're ready to start using the deleteOne() method!

Example of deleteOne Method in Mongoose

Let’s take a look at a practical example of how to use the deleteOne() method in Mongoose.

Example: Deleting a Document Based on Condition

This example uses the deleteOne function of mongoose to delete a specific document form the database. Below is a sample Node.js script that uses Mongoose to delete the first document that matches a condition:

// Filename: index.js 

const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});

// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});

// Function call
// Delete first document that matches
// the condition i.e age >= 10
User.deleteOne({ age: { $gte: 10 } }).then(function(){
console.log("Data deleted"); // Success
}).catch(function(error){
console.log(error); // Failure
});

Explanation:

  1. Database Connection: The mongoose.connect() method connects to a local MongoDB database named geeksforgeeks. If you're using a remote database, replace the connection string accordingly.
  2. User Model: The User model represents a collection where each document has name and age fields.
  3. Delete Operation: The deleteOne() method is called with a condition where age >= 10. It deletes the first matching document.
  4. Promise Handling: The .then() and .catch() blocks handle the success and failure of the operation.

Below is the sample data in the database before the deleteOne() function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Database after delete command

Run index.js file using below command:

node index.js

Output of above command

After running above command, you can see the data is deleted from the database.

When to Use deleteOne()?

The deleteOne() method is particularly useful when:

  • You need to delete only one document that meets the specified condition.
  • You are certain that deleting just one document based on a condition is sufficient for your use case.
  • You want to avoid deleting multiple documents, which could occur with remove().

Common Use Cases for deleteOne()

Here are some typical scenarios where deleteOne() is commonly used:

  1. Delete User Accounts: Remove a user document from the database based on unique criteria such as email or username.
  2. Remove Expired Sessions: Delete session documents from a session collection based on a timestamp condition.
  3. Delete Specific Items in a Collection: For example, delete an expired product listing or remove a blog post with a certain status.

Conclusion

In this guide, we explored how to use the deleteOne() method in Mongoose to delete a document from a MongoDB collection. By understanding the syntax, installation steps, and real-world examples, you can confidently implement this function in your Node.js applications. Make sure to always handle errors and consider edge cases such as when no documents match the condition. This ensures your applications remain stable and reliable when performing deletion operations.


Article Tags :

Explore