NoSQL: Deleting Data In A MongoDB Database

In the latest article of this series, we have started to explore the different types of query we can write when working in a MongoDB environment. In particular, we have focused our attention on writing code to retrieve data from the database. Today, we will move our attention to another important part of working with data in our application, removing it. 

Even if this might sound a little bit overrated it actually isn’t. Deleting data from our database is a very important operation that you will perform a lot in order to remove the data you don’t need anymore, deleting them in a good way is vital to ensure that your application is in a valid state and that you won’t encounter problems during the next stages of development.

Proper tools & proper terms

Like in the last article, since I’m gonna create a showcase of the various different queries you can write, my advice for you is to create a playground folder with a playground.js file. In this way, you will be able to execute and play around with the code without corrupting the rest of your project.

I would also like to mention that from now on, I’m going to refer to deleting data from a MongoDB database as removing them. The difference is not big, but since this is the terminology and syntax used by Mongo I wanted to specify this before proceeding.

A query for every goal

I will know show you all the different types of remove query we can write in a MongoDB environment. Keep in mind that in order to do this, I have created an example student called Mark using the beforeEach() method. In this way, before performing any operation we will know that there is such student into the database that is ready to be removed.

Let’s analyze the code

deleting data from mongoDB database code

And the code in it’s full glory –

const assert = require('assert');
const User = require('../src/student');

describe('Deleting a user', () => {
  let mark;

  beforeEach((done) => {
    mark = new Student({ name: 'mark' });
    http://mark.save ()
      .then(() => done());
  });

  it('model instance remove', (done) => {
    mark.remove()
      .then(() => Student.findOne({ name: 'mark' }))
      .then((student) => {
        assert(student === null);
        done();
      });
  });

  it('class method remove', (done) => {
    // Remove a bunch of records with some given criteria
    Student.remove({ name: 'mark' })
      .then(() => Student.findOne({ name: 'mark' }))
      .then((student) => {
        assert(student === null);
        done();
      });
  });

  it('class method findOneAndRemove', (done) => {
    Student.findOneAndRemove({ name: 'mark' })
      .then(() => Student.findOne({ name: 'mark' }))
      .then((student) => {
        assert(student === null);
        done();
      });
  });

  it('class method findByIdAndRemove', (done) => {
    Student.findByIdAndRemove(mark._id)
      .then(() => Student.findOne({ name: 'mark' }))
      .then((student) => {
        assert(student === null);
        done();
      });
  });
});

Model instance remove

As specified in previous articles, we can often use two different types of method to perform a specific task, class methods and instance methods. The first are provided to us as soon as we define a specific model, the second ones behave the same in this sense but can only be used on a specific instance of that model. In this case we have used both of them but let’s first analyze model instance removal:

delete with remove method

In this case the most difficult part to understand is just how the removal test is performed. First we take the mark Student we created in the beforeEach() method and apply the remove() method to it. This is enough to simply remove an instance from a database, but since we also want to test that this operation was completed correctly we also perform this operations:

  • Since this operation is asynchronous, we first attach a promise to the remove() method
  • Then we perform a query on our database using the class method findOne() to see if mark is still present into the database
  • We attach another promise to the findOne()method to check the result of this operation
  • If everything went good, we should now receive a null value as a response from the last query since mark was removed from the database.

Class method remove

At this point removing data from the database using a class method should result in an extremely easy operation since the only difference with what we have written earlier is that instead of referencing an instance we will use the Student model. You should use this type of removal when you have a specific criteria you want to use to remove documents from the database.

mongodb class method remove code

The findOneAndRemove() method

Another class method we can use is the findOneAndRemove()method. This method takes a set of specific criteria used for fetching the data we want to remove from our database but, instead of deleting all these data, it will only remove the first result from this set.

This means that even if we had thousands of students called ‘mark’ into a database, using these method we would still only have removed just the first one.

mongoDB findoneandremove method

The findByIdAndRemove() method

This method is quite easy to understand just by it’s name, In this case, we only use one criteria: the id of the document we want to fetch. Since every document has a unique id, also this method will return a record and, once we have that record fetched, we remove it.

mongodb find by id and remove code

Conclusion

In this article, we have further explored the different types of queries we can write in a MongoDB environment, in the next part, we will complete the circle and understand how to update data when working in such environment.

As always, keep in touch with me on Twitter @BorrelliDev or check out my blog thecoderswag.com.

NoSQL: Deleting Data In A MongoDB Database

You May Also Like

Leave a Reply

Your email address will not be published.