Nodejs MongoDB Drop Collection

MongoDB’s collection is like a table in RDMS. if you want to drop the collection then use dropCollection() method

Firstly create the drop_collection.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.dropCollection("users", function(err, res) {
      if (err) throw err;
       console.log("Collection is removed");
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the drop_collection.js file.


node drop_collection.js
Output:-
Collection is removed

Now, you can check collection is removed or not in MongoDB through command


> show collections