Node.js – Drop Database in MongoDB
In this Node.js Tutorial, we shall learn to Drop Database in MongoDB from Node.js Application with an example.
Example
Following is a step by step guide with an example to drop a database in MongoDB from Node.js Application.
- Start MongoDB Service. Run the following command to start MongoDB Service sudo service mongod start
- Get the base URL to MongoDB Service. A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell. While the Mongo Shell starts up, it echoes back the base url of MongoDB.arjun@nodejs:~$ mongoMongoDB shell version v3.4.9connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.9Server has startup warnings:2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]mongodb://127.0.0.1:27017
- Prepare the complete URL. Append the Database name you want to drop (say newdb), to the base URL. mongodb://127.0.0.1:27017/newdb
- Create a MongoClient. var MongoClient = require('mongodb').MongoClient;
- Make connection from MongoClient to the MongoDB Server with the help of URL. If the connection is successful, the db object points to the database newdb.MongoClient.connect(url, <callback_function>);
- Delete the Database using dropDatabase(callback) method. db.dropDatabase(<callback_function>);
- Close the connection to database. Once all the operations are done, close the db object. Note : In case of nested callback functions, which is the case in the below example, close the connection to database in the innermost callback function (or which gets executed last) to ensure that all the db operations are completed before closing connection. db.close();
Example Node.js program
// newdb is the database we drop var url = "mongodb://localhost:27017/newdb"; // create a client to mongodb var MongoClient = require('mongodb').MongoClient; // make client connect to 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 the database db.dropDatabase(function(err, result){ console.log("Error : "+err); if (err) throw err; console.log("Operation Success ? "+result); // after all the operations with db, close it. db.close(); }); }); |
arjun@tutorialkart:~/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 |
Conclusion :
In this Node.js MongoDB Tutorial – Node.js Drop Database in MongoDB, we have learnt to delete a database from Node.js Application using mongodb package. In our next tutorial – Node.js Create Collection in MongoDB, we shall learn to create a MongoDB Collection.