35-Nodejs Course 2023: Database Models: Crud Operations: Deleting Documents
Tags: node, typescript, mongodb, fastify
Published: 2022-11-04 02:47:24

---
title: 35-Nodejs Course 2023: Database Models: Crud Operations: Deleting Documents
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5jg6lqif92u9tzmlcgr.png
# Use a ratio of 100:42 for best results.
---

Now let's move to the last CRUD operation, which is deleting documents. We will use the `deleteOne` and `deleteMany` methods to delete documents from the database.

But we'll do it in a fancy way. We'll use one method to perform both operations. We'll use the `deleteOne` method to delete a single document and the `deleteMany` method to delete multiple documents.

## Delete method

We'll create a new method in the `Base` model called `delete`. This method will accept a `filter` object or a string, which represents the `_id` of the document to delete.

If the `filter` is an object, we'll use the `deleteMany` method to delete multiple documents. If the `filter` is a string, we'll use the `deleteOne` method to delete a single document.

```ts

// src/core/database/model/mode.ts

import { Collection, ObjectId } from "mongodb";
import connection, { Connection } from "../connection";
import { Database } from "../database";

/**
 * Base Model type that we need to define
 * to tell typescript that we're going to return a child that extends that base model
 * which will be the T (The child class)
 */
type BaseModel<T> = typeof Model & (new () => T);

export default abstract class Model {
  // ...
  
  /**
   * Delete a single document or multiple documents from the database
   */
  public static async delete<T>(
    this: BaseModel<T>,
    filter: ObjectId | Record<string, any>,
  ): Promise<number> {
    const query = this.query();

    if (filter.constructor.name === 'ObjectId') {
      const result = await query.deleteOne({
        _id: filter,
      });

      return result.deletedCount;
    } else {
      const result = await query.deleteMany(filter);

      return result.deletedCount;
    }
  }
}
```

As the `_id` is actually an object, we'll check for the constructor name of the filter object to determine if it is the `ObjectId` instance or not.

So now we can use the `delete` method to delete a single document or multiple documents based on the type of the `filter` argument.

```ts
// src/app/modules/users/routes.ts
  import User from "./models/user";

setTimeout(async () => {
  const user = await User.create({
    name: "hasan",
    email: "hassanzohdy@gmail.com",
  });

  const totalDeleted = await User.delete(user.data._id);

  // delete multiple documents
  const multipleDeleted = await User.delete({
    name: "hasan",
  });

  console.log(totalDeleted, multipleDeleted);
}, 4000);
```

Now we'll see that in the console, we'll get one for the single document and dozens for the multiple documents.

And that's it! We've finished the CRUD operations. Now we can create, read, update, and delete documents from the database.

## 🎨 Conclusion

We're now finally done with the CRUD operations basic principles, but we still have a lot of work to do. we didn't check for any failure of the database operations, we did some limitations over the database operations, for example the delete method we can not set a limit for how many records at most it should delete.

But don't worry, this is just the beginning. We'll continue to improve the database operations in the next chapters.

## 🎨 Project Repository

You can find the latest updates of this project on [Github](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) 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](https://www.youtube.com/playlist?list=PLGO8ntvxgiZMJc7RN2lIq9WmMOlWZGzmz), 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

- [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
- [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
- [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

- [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
- [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
- [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

- [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

- [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)