Mongoose delete array element in document and save

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

Favorite.updateOne({ cn: req.params.name }, {
    $pullAll: {
        favorites: req.params.deleteUid,
    },
});

To remove objects from array then

Favorite.updateOne({ cn: req.params.name }, {
    $pullAll: {
        favorites: [{_id: req.params.deleteUid}],
    },
});

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

Leave a Comment