Node.js – Drop Database in MongoDB

We can delete/drop a database from MongoDB through Node.js program.

In this Node.js Tutorial, we shall learn to Drop Database in MongoDB from Node.js Application with an example.

Dropping a MongoDB database is a permanent administration operation. The examples below show both the older callback style used in many legacy Node.js projects and the current async/await style used with recent versions of the official MongoDB Node.js driver. Use the command only after checking that you are connected to the correct MongoDB server and database.

What dropDatabase() Does in a Node.js MongoDB Application

The MongoDB dropDatabase() operation removes the current database, including its collections and indexes. In a Node.js application, the database to be dropped is selected from the connection string or by calling client.db("databaseName"). The method returns a result that indicates whether the database was dropped successfully.

For local testing, the database name is often appended to a URL such as mongodb://127.0.0.1:27017/newdb. For production deployments, the connection string may include authentication details, replica set options, or a MongoDB Atlas cluster host. The safety checks are the same: verify the target database name, use an account with the required permission, and close the client connection after the operation.

Reference: the official MongoDB manual documents the database drop behavior in db.dropDatabase().

Before You Drop a MongoDB Database from Node.js

Before running a Node.js script that drops a MongoDB database, check the following points.

  • Confirm the database name. A small typo in the connection string can point your script to a different database.
  • Do not run the script against a production connection string unless the database deletion is intended and approved.
  • Take a backup or snapshot if the data may be needed later.
  • Use an account with permission to drop the database. Without the required privileges, MongoDB returns an authorization error.
  • Avoid dropping internal databases such as admin, local, and config.

Steps to Drop Database in MongoDB via Node.js

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

Step 1: Start MongoDB Service.

Run the following command to start MongoDB Service

sudo service mongod start

Step 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.

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] 

While the Mongo Shell starts up, it echoes back the base url of MongoDB.

mongodb://127.0.0.1:27017

Step 3: 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

Step 4: Create a MongoClient.

</>
Copy
var MongoClient = require('mongodb').MongoClient;

Step 5: Make connection from MongoClient to the MongoDB Server with the help of URL.

</>
Copy
MongoClient.connect(url, <callback_function>);

If the connection is successful, the db object points to the database newdb.

Step 6: Delete the Database using dropDatabase(callback) method.

</>
Copy
db.dropDatabase(<callback_function>);

Step 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.

</>
Copy
db.close();

Example 1 – Drop Database from MongoDB via Node.js

In this example, we will drop a database named newdb.

node-js-mongodb-drop-database.js

</>
Copy
// 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();
	});
});

Output

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

Modern Node.js MongoDB dropDatabase() Example with async/await

If you are using a recent MongoDB Node.js driver, prefer the MongoClient async/await pattern. In this version, connect to the server, select the database with client.db("newdb"), call dropDatabase(), and close the client in a finally block.

drop-database-async.js

</>
Copy
const { MongoClient } = require("mongodb");

const uri = "mongodb://127.0.0.1:27017";
const databaseName = "newdb";

async function dropMongoDatabase() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db(databaseName);
    const result = await db.dropDatabase();

    console.log(`Database dropped: ${result}`);
  } catch (error) {
    console.error("Could not drop database:", error.message);
  } finally {
    await client.close();
  }
}

dropMongoDatabase();

Run the script from the terminal:

</>
Copy
node drop-database-async.js

A successful run prints a boolean result.

Database dropped: true

Dropping a MongoDB Database from the Node.js Command Line

For one-time local testing, you may prefer a short command instead of creating a separate JavaScript file. The following command connects to the local MongoDB server and drops the newdb database.

</>
Copy
node -e 'const { MongoClient } = require("mongodb"); (async () => { const client = new MongoClient("mongodb://127.0.0.1:27017"); await client.connect(); console.log(await client.db("newdb").dropDatabase()); await client.close(); })();'

Use this form carefully. A command-line one-liner is convenient, but it is also easy to run it from the wrong terminal history or with the wrong database name.

How to Verify That the MongoDB Database Was Dropped

After running the Node.js script, you can list databases in the MongoDB shell or mongosh to verify that newdb is no longer present.

</>
Copy
mongosh
show dbs

You can also check from Node.js by listing database names from the admin interface.

</>
Copy
const { MongoClient } = require("mongodb");

async function listDatabases() {
  const client = new MongoClient("mongodb://127.0.0.1:27017");

  try {
    await client.connect();

    const databases = await client.db().admin().listDatabases();
    console.log(databases.databases.map((db) => db.name));
  } finally {
    await client.close();
  }
}

listDatabases();

Common Errors When Node.js Cannot Drop a MongoDB Database

The following issues are common when dropDatabase() does not work as expected.

Error or symptomLikely causeWhat to check
ECONNREFUSEDMongoDB is not running or the host/port is wrong.Start MongoDB and verify the connection string.
Authentication failedThe username, password, or authentication database is incorrect.Check the credentials and auth source in the URI.
not authorizedThe user does not have permission to drop the database.Use a MongoDB user with the required database administration role.
false result or database still visibleThe script may have selected a different database.Print the target database name before calling dropDatabase().

Node.js MongoDB dropDatabase() Safety Checklist

  • Confirm that the script prints the intended database name before dropping it.
  • Keep production and test connection strings in separate environment variables.
  • Never hard-code a production MongoDB password in a tutorial, repository, or shared script.
  • Use try, catch, and finally so connection errors and cleanup are handled clearly.
  • Review the code path so dropDatabase() cannot run automatically during normal application startup.

Frequently Asked Questions on Node.js Drop Database in MongoDB

Does MongoDB dropDatabase() delete all collections in the database?

Yes. When dropDatabase() succeeds, MongoDB removes the selected database and its collections. Treat it as a destructive operation and keep a backup if the data may be needed later.

How do I drop a MongoDB database using Node.js async/await?

Create a MongoClient, connect to MongoDB, select the database with client.db("databaseName"), call await db.dropDatabase(), and close the client in a finally block.

Can I drop a MongoDB database from the command line with Node.js?

Yes. You can run a short Node.js command with node -e to connect and call dropDatabase(). This is useful for local test databases, but a script file is safer for repeated use because it is easier to review.

Why does Node.js show a MongoDB authorization error while dropping a database?

The connected MongoDB user may not have the permission required to drop the database, or the connection URI may authenticate against the wrong database. Check the username, password, authentication database, and assigned roles.

Should I use the old callback example or the async/await MongoDB example?

Use the callback example only when maintaining older Node.js code that already follows that style. For new code, the async/await example is easier to read and matches the style commonly used with recent MongoDB Node.js driver versions.

Editorial QA Checklist for This Node.js MongoDB Drop Database Tutorial

  • The tutorial clearly warns that dropping a MongoDB database permanently removes the selected database.
  • The database name newdb is used consistently in the URL, script, and output.
  • Legacy callback code remains available for older examples, while the async/await version is included for current Node.js projects.
  • New code blocks use PrismJS-compatible classes such as language-javascript, language-bash, and output.
  • The verification and troubleshooting sections help readers confirm the result and fix common connection or permission errors.

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.

For new applications, prefer the async/await MongoClient example and keep the database name separate from the base connection URI so it is easy to review before running the script.

In our next tutorial – Node.js Create Collection in MongoDB, we shall learn to create a MongoDB Collection.