DEV Community

Cover image for 35-Nodejs Course 2023: Database Models: Crud Operations: Deleting Documents
Hasan Zohdy
Hasan Zohdy

Posted on

35-Nodejs Course 2023: Database Models: Crud Operations: Deleting Documents

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.


// 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;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

// 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);
Enter fullscreen mode Exit fullscreen mode

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

😍 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)

Top comments (0)