What is findByIdAndDelete() in Mongoose?

The findByIdAndDelete() is a function in Mongoose used to find a document by the _id field and then remove the document from the collection.

It returns the document removed or deleted.

Syntax

Model.findByIdAndDelete(id)

Parameters

id: This is the id value. It is this value that is checked among all the documents by comparing their _id fields. If the document is found, then it is removed.

Return value

The deleted document is returned.

Example

In the example below, a Mongoose Schema was created, then the function findByIdandDelete() is called to delete a document in the collection.

// import mongoose
const mongoose = require("mongoose");
// creating a Schema with mongoose
let Product = mongoose.model("Product", new mongoose.Schema({
name: String,
price: Number
})
)
// find a document with id
let id = "60ff9d6fa676bb1334686840"
// find and delete document with the id
let product = await Product.findByIdAndDelete(id)
console.log(product)
/* OUTPUT
{name: "Pizza": price: 300}
*/

In the code above, the document with id 60ff9d6fa676bb1334686840 is deleted. Then, it is returned as {name: "Pizza", price: 300}

Free Resources