Mongoose Drop Collection If Exists

How to drop a collection if exist using mongoose in MongoDB?

From the title, it is clear that we are going to add some checks to avoid duplicate collection available in the database. This is a very important concept which almost needs to be used by every developer. This concept is really becoming a required thing from the small project to the big ones where a developer needs to work with various datasets and collections.

So in today’s tutorial, we are going to drop a collection if exist. Now I’m going to set up Node Project for this example. We are also going to write some other tutorials on mongoose where we use the same project to show the examples.

Before I move on let me tell you a few things Mongoose:

It is an Object Document Mapper (ODM).  ODM in mongoose is used to define objects. With Object Document Mapper (ODM), you can define strongly-typed schemas for MongoDB which maps them with documents.

I’m assuming that you have already installed node and MongoDB on your system. If you haven’t then look at our previous tutorials. Let’s get started with the project,

Let’s create a new directory for this project using “mkdir”

C:\>mkdir mongooseproject

Let’s get inside that directory

C:\>cd mongooseproject

Let’s initialize the node project:

C:\mongooseproject>npm init

Once you hit enter it will ask you some details. You can fill those details but they are optional. For this test project, I’m leaving it blank but you must fill it for your projects.

At the ends you will see a screen like this:

Image from Gyazo

Let’s install mongoose in our project first then after that we create a connection and insert some data.

C:\mongooseproject>npm install mongoose --save

Now we have installed the mongoose into our project. Once mongoose installed then after we need to create an index.js which is the entry point of application and need for running the application.

You can change the file name if you want to else I would recommend you go with this file for now. Let’s connect with our MongoDB server using Mongoose. To do that first we need to start our MongoDB server. You can start a MongoDB server in two ways one is graphical using Mongo Compass and the other one which cmd.

So let’s start with cmd, type in “mongod” and hit enter. Once you do that it will start your server and you will something similar as shown below in your command line:

Image from Gyazo

A message is shown in the last, showing that connection is waiting… The meaning of this message is that Mongo Server is looking for a client to connect with and play with the database. Let’s do that, here is the command that you need to enter but don’t close last opened cmd. Open another cmd and enter the command given below:

C:\>mongo -host localhost:27017

Don’t forget our goal. We are going to “drop if the collection exists”. To achieve the goal we first need to create a database and a collection.

Now I’m going to create a database and a collection.

>

use mongoosepractice

    >
    switched to db mongoosepractice >
    db.mongoosepractice.insertOne({
        "Name": "Patrick",
        "Age": 21
    }); > {

    "acknowledged": true,
    "insertedId": ObjectId("5d3c486ba35134f58358298f")

}

With the above code, we have created a database with the name “mongoosepractice” and we have created a collection with the same name as database “mongoosepractice”.

You can see this in the MongoDB Compass as shown below:

Image from Gyazo

After that, we have inserted a document or you can say a record with name and age.

Image from Gyazo

So finally, we have created everything to implement our task.

You can drop collection in two ways, the first one which is easy but not recommended. You can go to MongoDB Compass and delete “collection” and there is an icon given to do that. You can see the picture below:

Image from Gyazo

How to drop a collection if exists using Mongoose?

Now, we have everything installed in our system. Let’s add some in our node application to complete our task.

Let’s create a connection using mongoose from our index.js file:

Here, the code is given that you need to put in index.js file:

const mongooseconnection = require("mongoose");
mongooseconnection.connect("mongodb://127.0.0.1:27017/mongoosepractice", {
    useNewUrlParser: true
});
const connection = mongooseconnection.connection;
connection.once("open", function() {
    console.log("MongoDB connected successfully");
});

After adding the code run the index.js file using the command:

C:\mongooseproject>node index.js

You will see a successfully connected connection in the result. You can see the picture below:

Image from Gyazo

Let’s get our hands dirty with some mongoose code. First, I would like to show the insertion of data via mongoose. In mongoose, you have to define a schema which basically tells about the type of data you want to use in Mongo. This is the “Model” which is used to create an instance for the data you to store in the database.

Here I have created another file with the name of “mongoosemodel.js” which contains schema and model.

mongoosemodel.js

var mongoose = require("mongoose");
var userProfile = new mongoose.Schema({
    name: {
        type: String
    },
    age: {
        type: Number
    }
});
module.exports = mongoose.model("userProfile", userProfile);
var newUser = mongoose.model("userProfile", userProfile);
var userOne = new newUser({
    name: "Sam",
    age: "20"
});

userOne.save(function(error) {
    console.log("User One has been saved!");
    if (error) {
        console.error(error);
    }
});

In the above code, we have created a userProfile schema where we want to get the name and age of the user. To do that, we have mongoose. Schema method to define the schema.

After that step, we have created a model through which you can add some data to the database. 

And in the last line, we have used a save method to save the data inside the database.  Once you add this code, you need include this file in the main file index.js . You can do that by using a single line of code.

const Profile = require("./mongoosemodel.js");

After that, you need to run the app using,

C:\mongooseproject>node index.js

OR

C:\mongooseproject>npm start

Next thing, I would like to show how the data is represented in the database. Look at the picture below in MongoDB Compass:

Image from Gyazo

You can see that we have created a schema with the name “userprofiles” which is created as a collection in MongoDB.

We have also inserted a record or as Mongo refers to them, a document. The document is also shown in the collection…

Image from Gyazo

Now our main task is to check that if the collection exists then drop that collection.  You have to update the index.js code and replace with the code given below. I’ll give a brief of how the code is working.

Index.js Code Snippet

const mongooseconnection = require("mongoose");
mongooseconnection.connect("mongodb://127.0.0.1:27017/mongoosepractice", {
    useNewUrlParser: true
});
const connection = mongooseconnection.connection;
connection.once("open", function() {
    console.log("MongoDB connected successfully");
    connection.db.listCollections().toArray(function(err, names) {
        if (err) {
            console.log(err);
        } else {
            for (i = 0; i < names.length; i++) {
                console.log(names[i].name);
                if ((names[i].name = "userprofiles")) {
                    console.log("Userprofile Collection Exists in DB");
                    mongooseconnection.connection.db.dropCollection(
                        "userprofiles",
                        function(err, result) {
                            console.log("Collection droped");
                        }
                    );
                    console.log("Userprofile Collection No Longer Available");
                } else {
                    console.log("Collection doesn't exist");
                }
            }
        }
    });
});

const Profile = require("./mongoosemodel.js");

Index.js Screenshot

Image from Gyazo

First few lines are the same. So here I’m going explain from connection.once("open", function() {…}); from where database connection open up.  We show a message after checking that MongoDB is connected or not.

console.log("MongoDB connected successfully");

In the next line, we are listing all the collection present inside the database in an array format.

connection.db.listCollections().toArray(function(err, names) {

After that, we are also checking for any kind error using if statement and there is any error then it will show up on console using console.log file. If there is no error found then it will pass to else part where we run a loop.

for (i = 0; i < names.length; i++) {

With the loop, we are returning the name of collections print them on the console.

for (i = 0; i < names.length; i++) {
    console.log(names[i].name);

In the next line, we are checking for the collection with its name if present in the database.

if ((names[i].name = "userprofiles")) {
    console.log("Userprofile Collection Exists in DB");

If the above condition is true then it will go the next line and print that statement. After that, it will go to the next line where the code is written to drop the collection.

mongooseconnection.connection.db.dropCollection("userprofiles", function(
    err,
    result
) {
    console.log("Collection droped");
});

dropCollection() is a method in mongoose to delete the collection from the database.

Finally, we have to achieve our goal. We have first created everything from scratch and the list the collections inside the database. After that, we have added a check that the collection exists or not and if exists then delete that.

Let’s verify this. So we are going to check using MongoDB compass that collections are deleted or not. You can easily see that we have only one collection left which “mongoosepractice”.

Image from Gyazo

Conclusion

This concludes our demo on how to drop a collection only if it exists using the mongoose Node.js library for MongoDB. We hope this was informative for you. Thank you so much for reading and please don’t hesitate to reach out to us at Object Rocket if you need any help with your MongoDB data. Thanks!

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.