seeking best approach to remove deleted products from users' favourites

Viewed 13

in my MERN website users can view products and add them to their favourites list (array in mongoose schema) by id, however, products can be deleted by their owners or website admin, so i need a way to clear the deleted products ids from the favourites lists of all users..using node and mongoose the basic approach that comes to mind is this:

update all the users to remove the product's id from their favourites

router.delete("/:id", (req, res) => {
    let id = req.params.id;
    Product.findById(id).then(place => {
            Product.deleteOne({ _id: id }).then(result => {
                User.updateMany({},{$pull: { favourites: id }}).then(result=>{
                    res.sendStatus(200)
                }).catch(err => {
                console.log(err);
                res.sendStatus(400);})
    })
})

but going through all user's documents to do this just doesn't seem right..what's a better approach to do this?

0 Answers
Related