DEV Community

Cover image for 44-Nodejs Course 2023: Destroying The Model
Hasan Zohdy
Hasan Zohdy

Posted on

44-Nodejs Course 2023: Destroying The Model

We've proceeded with a nice progress in the saving process, now let's go to the deleting step of the model.

Destroy Method

It actually works exactly like the delete method except that the destroy method will be called from the model itself directly.

// src/core/database/model/model.ts
  /**
   * Delete the document from database
   */
  public async destroy() {
    await queryBuilder.deleteOne(this.getCollectionName(), {
      _id: this.data._id,
    });
  }
Enter fullscreen mode Exit fullscreen mode

Nothing new here, we just called the query builder to delete the document from the database.

Now the model will keep the data in the memory, but it will be deleted from the database.

Let's give it a try

import User from './models/users';

const user = await User.find(1);

if (user) {
    await user.destroy();
}
Enter fullscreen mode Exit fullscreen mode

And that's it!

But what if we called it in a model that does not have an id?

In that case we shall skip the deletion process and just return the model instance.

// src/core/database/model/model.ts
  /**
   * Delete the document from database
   */
  public async destroy() {
    if (! this.data._id) return;

    await queryBuilder.deleteOne(this.getCollectionName(), {
        _id: this.data._id,
      });
  }
Enter fullscreen mode Exit fullscreen mode

🎨 Conclusion

We added a new method called destroy which will delete the document from the database using the model itself.

🚀 Project Repository

You can find the latest updates of this project on Github

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on Youtube, the course is in Arabic language.

💰 Bonus Content 💰

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay