How to delete existing file when update post with node js and react js?

204 views Asked by At

Actually I store the image in local storage and Date+file name store in Mongoose data base. but when I delete or update post/product how can I find the specific existing file to delete?

//update products
const updateProducts = (req, res, next) => {
  const id = req.params.id
  const image = req.body.image
  const pdf = req.body.pdf
  const trade_name = req.body.trade_name
  const generic_name = req.body.generic_name
  const therapeutic_class = req.body.therapeutic_class
  const description = req.body.description
  const indication = req.body.indication
  const dosage_and_administration = req.body.dosage_and_administration
  const supply = req.body.supply
  const keyword = req.body.keyword

  const updates = {
      trade_name,
      generic_name,
      therapeutic_class,
      description,
      indication,
      dosage_and_administration,
      supply,
      keyword,
  }
  if (image) {

    fs.unlink(`uploads/${image}`, function(err){
      if (err) console.log("No file found")
    })
    updates.image = image
  } 
  if (pdf) {
    updates.pdf = pdf
  }
  productsSchema.findOneAndUpdate({_id:id}, {
    $set: updates
  }, {
    new: true
  })
  .then(data => {
    if (!data){
      res.status(404).send({
        message: `Cannot update with id ${id}`
      })
    } else res.send({message: "Successfully update: ", data})
  })
  .catch(err => {
    console.log(err)
    res.status(500).send({
      message: "Error updating Hub Address",
      
    })
  })
}

this is my update api code, I received date+filename from frontend as a req.body.image. the problem is I attached date in the name which is unique that's why next time I can't find is by name. May I use the post id as a image name? when I will do for multiple image for 1 product?

0

There are 0 answers