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

Updated: December 30, 2023 By: Guest Contributor Post a comment

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.