Create a util file under util folder named file.js
const fs = require('fs');
const deleteFile = (filePath) => {
fs.unlink(filePath, (err) => {
if (err) {
throw (err);
}
})
}
exports.deleteFile = deleteFile;
const fileHelper = require('../util/file'); // importing
exports.postDeleteProduct = (req, res, next) => {
const productId = req.body.productId; // Take productId from request
Product.findById(productId) // find product in the database
.then(product => {
if(product) {
fileHelper.deleteFile(product.imageUrl); // delete the image file
return Product.deleteOne({_id: productId, userId: req.user._id}) // delete the product record from the database
} else {
return next(new Error('PRODUCT NOT FOUND.')); // if no product found with the id
}
}).then(result => {
if (result.n > 0) {
console.log("PRODUCT DELETED!"); // if product successfully got deleted
res.redirect('/admin/products');
} else {
throw new Error("EITHER USER UNAUTHORIZED TO DELETE OR PRODUCT NOT FOUND");
}
}).catch(err => {
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
});
}
Comments
Post a Comment