Sling Academy
Home/Node.js/Mongoose Model.findByIdAndRemove() function explained (with examples)

Mongoose Model.findByIdAndRemove() function explained (with examples)

Last updated: December 30, 2023

The Model.findByIdAndRemove() function in Mongoose is a convenient method that combines finding a document by ID and removing it from the collection. This function has been part of Mongoose since its early versions, providing a streamlined way to handle the deletion of documents.

findByIdAndRemove() is particularly useful when you need to delete a single document and know its unique identifier. It simplifies removing documents by encapsulating what would otherwise be a two-step process (finding and then removing) into a single operation.

Syntax and Parameters

Model.findByIdAndRemove(id, [options], [callback])
  • id: The unique identifier (_id) of the document you want to remove.
  • options: (Optional) A options object that may contain various properties like select, session, etc.
  • callback: (Optional) A function to execute after the operation completes. It follows Node.js’s convention of function(error, doc).

Returned value: If no callback is passed, it returns a promise that resolves to the document that was removed if the operation is successful.

Code Examples

1. Async/Await Syntax Example

Summary: Using async/await to remove a document by ID.

const mongoose = require('mongoose');
const { Schema } = mongoose;

mongoose.connect('mongodb://localhost:27017/mydatabase');

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

async function removeDocumentById(id) {
  try {
    const result = await MyModel.findByIdAndRemove(id);
    console.log('Removed document:', result);
  } catch (error) {
    console.error('Error removing document:', error);
  }
}

removeDocumentById('someDocId');

2. Callback Syntax Example

Summary: Using the traditional callback style to remove a document.

const mongoose = require('mongoose');
const { Schema } = mongoose;

mongoose.connect('mongodb://localhost:27017/mydatabase');

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

MyModel.findByIdAndRemove('someDocId', (error, doc) => {
  if (error) {
    console.error('Error removing document:', error);
  } else {
    console.log('Removed document:', doc);
  }
});

Conclusion

The Model.findByIdAndRemove() method in Mongoose provides a convenient and high-level abstraction for removing documents by their ID, making code easier to write, understand, and maintain. Although it’s deprecated in newer versions of Mongoose in favor of the more versatile findOneAndRemove, it is still a useful method to know for quick operations or maintaining legacy code.

Next Article: Understanding the Mongoose Model.updateOne() Function in Node.js

Previous Article: Mongoose findByIdAndDelete() function (with examples)

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