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.


Following is a step by step guide with an example to drop a database in MongoDB from Node.js Application.

  1. Start MongoDB Service. Run the following command to start MongoDB Service
  2. 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.
  3. Prepare the complete URL. Append the Database name you want to drop (say newdb), to the base URL.
  4. Create a MongoClient.
  5. 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.
  6. Delete the Database using dropDatabase(callback) method.
  7. 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.

Example Node.js program

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.