Categories
JavaScript Answers

How to delete array element in document and save with Mongoose?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *