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.
Model.findByIdAndDelete(id)
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.
The deleted document is returned.
In the example below, a Mongoose Schema was created, then the function findByIdandDelete()
is called to delete a document in the collection.
// import mongooseconst mongoose = require("mongoose");// creating a Schema with mongooselet Product = mongoose.model("Product", new mongoose.Schema({name: String,price: Number}))// find a document with idlet id = "60ff9d6fa676bb1334686840"// find and delete document with the idlet 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}