![]() |
VOOZH | about |
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.
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.findOneAndDelete() in MongooseHereโ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);
}
});
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.
You can visit the link to Install mongoose module. You can install this package by using this command.
npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.
npm version mongooseAfter 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.jsThe project structure will look like this: ๐ Image
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
To execute the code, open the terminal, navigate to the folder containing index.js, and run the following command:
node index.js๐ ImageAfter running the findOneAndDelete() function, the first matching document (e.g., "Alice" with age 25) will be deleted, and the database will look like this:
findOneAndDelete()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.
findOneAndDelete()?findOneAndDelete() provides a simple and clear way to delete a document by specifying a filter condition.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.