0

In the code given below:-

var Image = mongoose.model("Image", imageSchema); //Assuming all the configuration of packages are done
app.delete("/element/:id", function(req, res) {
  Image.findByIdAndRemove(req.params.id, function(err) {
    if(err) {
      //Error Handling
    } else {
      fs.remove(path, function(err) { //where path is the path of the image and fs is fs-extra
        if(err) {
          //Error Handling
          } else {
            res.send("Image deleted!");
          }
      });
    }
  });
});  

Supposing Mongoose successfully deleted the Data from the database. But fs(i.e. fs-extra) is unable to delete the image. Then there will be a scenario where the data is deleted but the image still exists. So is there a way to handle this type of situation?

1 Answers1

0

Use fs.unlink instead of fs.remove.

var Image = mongoose.model("Image", imageSchema); //Assuming all the configuration of packages are done
app.delete("/element/:id", function(req, res) {
  Image.findByIdAndRemove(req.params.id, function(err) {
    if(err) {
      //Error Handling
    } else {

fs.unlink(path+req.file.filename, (err) => {
        if (err) {
            console.log("failed to delete local image:"+err);
        } else {
            console.log('successfully deleted local image');                                
        }
});
    }
  });
});
Asif vora
  • 3,163
  • 3
  • 15
  • 31