Open In App

Mongoose findOneAndDelete() Function

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

The findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In this article, we’ll explore how to use findOneAndDelete() effectively, along with its syntax, use cases, and practical examples.

What is the Purpose of findOneAndDelete() in Mongoose?

The findOneAndDelete() function is used to locate a single document that matches a specified filter and delete it from the database. Once the document is found, it is removed, and the deleted document (if found) is passed to the callback function. If no matching document is found, null is returned.

This function is commonly used in Node.js applications with Mongoose to manage data removal in MongoDB efficiently. Unlike other methods like remove(), findOneAndDelete() is a more modern approach, offering clearer syntax and better support for asynchronous operations.

Syntax

Model.findOneAndDelete(filter, options, callback);

Parameters:

  • filter: A query object used to specify the conditions for the document to be deleted.
  • options (optional): An object that may contain additional options like sort, projection, etc.
  • callback (optional): A function that is executed after the operation completes. It provides an error (if any) and the deleted document.

Example: Using findOneAndDelete() in Mongoose

Here’s an example demonstrating how to use the findOneAndDelete() method to delete a user document based on an age 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 }
});

// Find only one document matching the
// condition(age >= 5) and delete it
User.findOneAndDelete({age: {$gte:5} }, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Deleted User : ", docs);
}
});

Step-by-Step Guide to Using findOneDelete()

In this article, we’ll show you how to use the findOneAndDelete() method in Mongoose to delete a document based on a filter. Follow the steps to set up your project and implement this simple yet powerful function for document deletion.

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: Check Mongoose Version

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

npm version mongoose


Step 3: Set Up 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


The project structure will look like this:

Step 4: Write the Code

In index.js, write the code provided in the previous example to establish a connection with MongoDB and demonstrate the use of findOneAndDelete().

Below is the sample data in the database before the 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

Step 5: Run the Code

To execute the code, open the terminal, navigate to the folder containing index.js, and run the following command:

node index.js

After running the findOneAndDelete() function, the first matching document (e.g., "Alice" with age 25) will be deleted, and the database will look like this:

new Database

Return Value of findOneAndDelete()

  • Success: If the document is deleted successfully, the deleted document is passed to the callback.
  • Failure: If no document matches the filter, the callback returns null.

The return value of findOneAndDelete() makes it easy to track the removed data and handle it for further use, such as logging or processing.

Why Use findOneAndDelete()?

  • Clear and Simple Syntax: findOneAndDelete() provides a simple and clear way to delete a document by specifying a filter condition.
  • Supports Both Callback and Promise Syntax: This method works seamlessly with both callback-based and promise-based implementations, making it compatible with modern async/await syntax.
  • Efficient Performance: The method is optimized for deleting a single document and returns the deleted document, allowing for minimal overhead and fast execution.

Conclusion

The findOneAndDelete() function in Mongoose is an efficient and straightforward way to delete a single document based on a filter condition. It provides a clear syntax, easy handling of asynchronous operations, and the ability to return the deleted document. This makes it an ideal choice for applications that require frequent document deletions in MongoDB. By using findOneAndDelete(), developers can easily manage data deletion tasks while ensuring smooth and efficient operations in Node.js applications.


Next Article

Similar Reads