sauceCtrl_deleteSauce

PHOTO EMBED

Wed Sep 08 2021 16:22:28 GMT+0000 (UTC)

Saved by @devdave

exports.deleteSauce = (req, res, next) => {
  // finds object in database
  Sauce.findOne({ _id: req.params.id })
    .then((sauce) => {
      // extract filename
      const filename = sauce.imageUrl.split("/images/")[1];
      // delete file thanks to unlink
      fs.unlink(`images/${filename}`, () => {
        // in callback: once file is deleted => deletes object from database
        Sauce.deleteOne({ _id: req.params.id })
          .then(() => res.status(200).json({ message: "Objet supprimé !" }))
          .catch((error) => res.status(400).json({ error }));
      });
    })
    .catch((error) => res.status(500).json({ error }));
};
content_copyCOPY