Open In App

How to Remove Documents using Node.js Mongoose?

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:Abdullah123@cluster0.ihx3lfc.mongodb.net/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.


Article Tags :