In this part of the mongodb operations using node.js tutorial series , we will learn about how we can
drop
a mongodb collection using node.js
.
We will start by including mongodb
npm package as shown below :
var mongo = require('mongodb');
Establish a connection between the mongoDb database and our node.js app using the following :
var new_db = "mongodb://localhost:27017/demo_db"
There are 2 methods with which we can drop a collection in mongodb which are expained with example below.
db.collection("NAME_OF_THE_COLLECTION").drop( (CALLBACK_FUNCTION) => {});
//drop.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("Dropped successfully");
db.close();
});
});
>node drop.js
Dropped successfully
db.dropCollection("NAME OF THE COLLECTION" , (CALLBACK FUNCTION) => {});
//dropcollection.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("Dropped successfully");
db.close();
});
});
>node dropcollection.js
Dropped successfully
In this article we learned about
monogdb
npm package in your app. drop()
method in mongodb to delete a collection using node.jsdropCollection()
in mongodb to delete a collection using node.js