Sometimes, we want to delete array element in document and save with Mongoose.
In this article, we’ll look at how to delete array element in document and save with Mongoose.
How to delete array element in document and save with Mongoose?
To delete array element in document and save with Mongoose, we can use the updateOne
method with the $pullAll
operator.
For instance, we write
Favorite.updateOne({
name
}, {
$pullAll: {
favorites: req.params.deleteUid,
},
});
to call updateOne
with an object to search for the document with the name
value set to name
.
The 2nd object has the $pullAll
property which lets us remove the favorites
entries in the selected Favorite
document with the _id set to req.params.deleteUid
.
Conclusion
To delete array element in document and save with Mongoose, we can use the updateOne
method with the $pullAll
operator.