In this Chapter , we will learn about deleting the collection in mongodb using nodejs
Step - 1 : Including Packages
We will start by
requiring the package.
We are using the following package in our application :
var mongo = require('mongodb');
Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.
var new_db = "mongodb://localhost:27017/demo_db"
Step - 3 : DROP the collection
There are 2 ways to drop the collection in mongodb using nodejs which are as follows :
db.collection("NAME_OF_THE_COLLECTION").drop( (CALLBACK_FUNCTION) => {
//deleteCollection-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//Connecting to the database
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//ACCESSING A COLLECTION IN MONGODB USING NODE.JS
db.collection("new").drop( (err , collection) => {
if(err) throw err;
if(collection) console.log("Table Deleted successfully");
db.close();
});
});
D:\nj-learn-mongo>node deleteCollection-mongodb-nodejs.js
D:\nj-learn-mongo>node deleteCollection-mongodb-nodejs.js
Table Deleted successfully
db.dropCollection("NAME OF THE COLLECTION" , (CALLBACK FUNCTION) => {});
//dropcollection-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//Accessing the collection
db.dropCollection("details" , (err , collection) => {
if(err) throw err;
if(collection) console.log("Table Deleted successfully");
db.close();
});
});
D:\nj-learn-mongo>node dropcollection-mongodb-nodejs.js
D:\nj-learn-mongo>node dropcollection-mongodb-nodejs.js
Table Deleted successfully