English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this Node.js tutorial, we will learn how to delete a database from MongoDB in a Node.js application through an example.
Here is a step-by-step guide, along with an example of deleting a database from a MongoDB into a Node.js application.
Start the MongoDB service. Run the following command to start the MongoDB service
sudo service mongod start
Get the basic URL of the MongoDB service. To understand the basic URL of the MongoDB service, a simple trick is to open the terminal and run the Mongo Shell.
Terminal-Mongo Shell
arjun@nodejs:~$ mongo MongoDB shell version v3.4.9 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.9 Server has startup warnings: 2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]
When the Mongo Shell starts, it echoes the basic URL of MongoDB.
mongodb://127.0.0.1:27017
Prepare the complete URL. Attach the name of the database to be deleted (e.g., newdb) to the basic URL.
mongodb://127.0.0.1:27017/newdb
Create a MongoClient.
var MongoClient = require('mongodb').MongoClient;
Connect to the MongoDB server with the help of the URL using MongoClient.
MongoClient.connect(url, <callback_function>);
If the connection is successful, the db object points to the database newdb.
Use the dropDatabase(callback) method to delete the database.
db.dropDatabase(<callback_function>);
Close the connection to the database. After completing all operations, close the db object. Note: For nested callback functions (as shown in the example below), close the connection to the database (or execute lastly) in the innermost callback function to ensure that all database operations are completed before closing the connection.
db.close();
// newdb is the database we deleted var url = "mongodb://localhost:27017/newdb"; // Create a client to mongodb var MongoClient = require('mongodb').MongoClient; // Make the client connect to the mongo service MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Connected to Database!"); // Print Database Name console.log("db object points to the database: ");+ db.databaseName); // Delete Database db.dropDatabase(function(err, result){ console.log("Error: ");+err); if (err) throw err; console.log("Operation Success? ");+result); // Close db after completing all operations with it. db.close(); }); });
Output Result
arjun@w3codebox:~/workspace/nodejs/mongodb$ node node-js-mongodb-drop-database.js Connected to Database! db object points to the database: newdb Error: null Operation Success? true
In this Node.js MongoDB tutorial – Placing Node.js in the database of MongoDB, we learned how to delete the database from the Node.js application using the mongodb package. In our next tutorial – Creating Collections in MongoDB with Node.js, we will learn how to create MongoDB collections.