How to Use findByIdAndDelete in Mongoose: Syntax and Example
Use
findByIdAndDelete(id) in Mongoose to find a document by its ID and delete it in one step. It returns the deleted document if found, or null if no document matches the ID.Syntax
The findByIdAndDelete method takes the document's id as the first argument and an optional options object or callback. It returns a promise that resolves to the deleted document or null if no document was found.
- id: The unique identifier of the document to delete.
- options (optional): Additional settings like
projectionto specify fields to return. - callback (optional): Function to handle the result or error.
javascript
Model.findByIdAndDelete(id, [options], [callback])
Example
This example shows how to delete a user by their ID using findByIdAndDelete. It connects to MongoDB, defines a simple User model, deletes a user by ID, and logs the deleted document.
javascript
const mongoose = require('mongoose'); async function run() { await mongoose.connect('mongodb://localhost:27017/testdb'); const userSchema = new mongoose.Schema({ name: String, age: Number }); const User = mongoose.model('User', userSchema); // Create a user to delete const newUser = await User.create({ name: 'Alice', age: 30 }); // Delete the user by ID const deletedUser = await User.findByIdAndDelete(newUser._id); console.log('Deleted user:', deletedUser); await mongoose.disconnect(); } run().catch(console.error);
Output
Deleted user: { _id: ObjectId("..."), name: 'Alice', age: 30, __v: 0 }
Common Pitfalls
- Passing an invalid or non-existent
idwill returnnullwithout error, so always check the result. - Not awaiting the promise or missing a callback can cause unexpected behavior.
- Using
findByIdAndRemoveis similar but considered legacy; preferfindByIdAndDelete. - Ensure the ID is a valid
ObjectIdstring to avoid cast errors.
javascript
/* Wrong: Not awaiting the deletion */ User.findByIdAndDelete('invalidId'); // No error thrown but no deletion confirmed /* Right: Await the promise and check result */ const deleted = await User.findByIdAndDelete('validObjectId'); if (!deleted) { console.log('No document found with that ID'); }
Quick Reference
| Parameter | Description |
|---|---|
| id | The unique document ID to find and delete |
| options | Optional settings like projection or session |
| callback | Optional function to handle result or error |
| Returns | Promise resolving to deleted document or null |
Key Takeaways
Use findByIdAndDelete(id) to delete a document by its ID in one step.
Always await the method or use a callback to handle the result properly.
Check if the returned value is null to know if a document was deleted.
Pass a valid ObjectId string to avoid casting errors.
Prefer findByIdAndDelete over the legacy findByIdAndRemove method.