Sling Academy
Home/Node.js/Mongoose findByIdAndDelete() function (with examples)

Mongoose findByIdAndDelete() function (with examples)

Last updated: December 30, 2023

The findByIdAndDelete() function is a part of Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js which provides a higher level of abstraction than the native driver. This function was introduced as a shorthand for finding a document by its ID and then removing it from the collection.

The main purpose of findByIdAndDelete() is to provide a simple and straightforward way to delete a document based on its unique identifier (_id). It combines the functionality of finding a document and deleting it into a single operation, simplifying the code required to accomplish this common task.

Syntax and Parameters

Model.findByIdAndDelete(id, [options], [callback])
  • id: the unique ID of the document you wish to delete.
  • options: optional settings for the query. For example, setting { new: true } will return the document as it was before deletion.
  • callback: an optional function to run once the operation is complete. If not provided, the function will return a promise.

The function returns a promise resolving to the deleted document, or the value returned is according to the options specified, if any.

Examples

Basic Deletion Example

Deleting a document by its ID:

import mongoose from 'mongoose';
const { Schema } = mongoose;

const itemSchema = new Schema({ name: String });
const Item = mongoose.model('Item', itemSchema);

async function deleteItem(id) {
  try {
    const deletedItem = await Item.findByIdAndDelete(id);
    console.log('Deleted item:', deletedItem);
  } catch (error) {
    console.error('Error deleting item:', error);
  }
}

Option Use Example

Using options with findByIdAndDelete:

async function deleteItemWithOptions(id) {
  try {
    const deletedItem = await Item.findByIdAndDelete(id, { new: true });
    if (deletedItem) {
      console.log('Document to be deleted:', deletedItem);
    } else {
      console.log('No document found with that id.');
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

Conclusion

Mongoose’s findByIdAndDelete() function is an efficient and concise way to remove documents by their ID in Node.js applications. It reduces the complexity of code, and properly handling the returned promise brings clarity and better error management to your application logic. Reliable deletion operations are critical in maintaining data integrity, and through the use of this Mongoose feature, developers have a powerful tool in their arsenal for managing MongoDB collections.

Next Article: Mongoose Model.findByIdAndRemove() function explained (with examples)

Previous Article: Mongoose: Sorting Documents by Multiple Fields

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates