Mongoose Schema Connection.prototype.dropCollection() API
Last Updated :
14 Dec, 2022
The Connection.prototype.dropCollection() method of the Mongoose API is used on the Connection object. It allows us to delete particular collections from the MongoDB database. With the help of this method, we can remove any collection from the database along with all the documents and indexes associated with it. Let us understand dropCollection() method using an example.
Syntax:
connection.dropCollection( <collection>, <callback> );
Parameters: This method accepts two parameters as described below:
- collection: It is used to specify the name of the collection that we want to drop from the database.
- callback: It is used to specify the callback function which will get executed after the dropCollection() method ends its execution.
Return Value: If the callback function is not provided, this method returns a promise.
Setting up Node.js Mongoose Module:
Step 1: Create a Node.js application using the following command:
npm init
Step 2: After creating the NodeJS application, Install the required module using the following command:
npm install mongoose
Project Structure: The project structure will look like this:
Database Structure: The database structure will look like this, the following database is present in the MongoDB.
Example 1: The below example illustrates the basic functionality of the Mongoose Connection dropCollection() method, using the callback function.
Filename: app.js
Javascript
const mongoose = require( "mongoose" );
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true ,
useUnifiedTopology: true ,
});
connectionObject.dropCollection( 'test1' , (error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
})
|
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
true
GUI Representation of the Database using Robo3T GUI tool:
Example 2: The below example illustrates the basic functionality of the Mongoose Connection dropCollection() method, using promise.
Filename: app.js
Javascript
const mongoose = require( "mongoose" );
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true ,
useUnifiedTopology: true ,
});
connectionObject.dropCollection( 'testCreateCollection' ).
then(success => {
console.log(success);
}). catch (err => console.log(err))
|
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
true
GUI Representation of the Database using Robo3T GUI tool:
Reference: https://mongoosejs.com/docs/api/connection.html#connection_Connection-dropCollection
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...