node.jsexpressmongoosecloudinary

Delete image with full url from cloudinary not working - Nodejs


I am trying to delete image from cloudinary via my express app, it is working only when i shorten the url to match the cloudinary folder that i created

pictures : "Images/zebre_s2gtto"

the full url of my image is

https://res.cloudinary.com/beloved/image/upload/v1589562378/Images/zebre_s2gtto.jpg

the main problem is that the image url is stored in the database and contains the full image url.

when i want to delete the image from cloudinary and from my database, if i mention the full url, the image is deleted from my database but not in cloudinary and if i mention the short url from cloudinary, image is deleted from cloudinary but the url is not deleted from my database because mongo is waiting for the full url of the image and cloudinary requires the shortened url.

my mongoose schema

{
  pictures : Array
}

what i am trying to do

deletePictures = async (req, res) => {
  const img = req.body.pictures
  try {
    await cloudinary.v2.uploader.destroy(
      img, { invalidate: true, resource_type: "image" }, async (error, result)=> {
      if (error){
        return res.status(400).json(error)
      }
       await  Property.updateOne({$pull : { pictures: img }});
      res.json(result)
      })
  }
  catch (e) {
    res.status(500).json('Something went wrong')
  }
};

the postman test with PUT method

{
    "pictures" : "https://res.cloudinary.com/beloved/image/upload/v1589562378/Images/zebre_s2gtto.jpg"
}


Solution

  • There isn't a way to delete resources from Cloudinary via the URL and you need to use the public_id (i.e. the 'short URL' you refer to). The most common workflow is to store the public_id in your database as that is used for all API operations (delete, update etc). For URL generation, you can use the public_id and pass that into the Cloudinary SDK helper methods which construct the URLs locally and output the URL to the asset. These methods can be given any set of transformations options too. Please see the following section for examples for each SDK - https://cloudinary.com/documentation/image_transformations#embedding_images_in_web_pages

    I would recommend you migrate away from storing URLs and update your database to reference and keep the public_id. You can run a one-off script to extract the public_id from your existing URLs and then update the schema accordingly for your current records. For new uploads, you can grab the public_id parameter from the API response directly.