I’m having a problem overwriting the existing image that belongs to a product with a new one. My new image is uploaded locally but not in my database (MongoDB Atlas) The update seems to replace the original picture with a blank one. This is what my code looks like:
This is my file storage and constraints
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, process.cwd() + '/public/uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
}})
const upload = multer({
dest: 'uploads',
storage: storage,
fileFilter(req, file, cb) {
if (!file.originalname.match(/.(jpg|png)$/)) {
return cb(new Error('Please upload picture in jpg/png format'))
}
cb(undefined, true)
}});
This is my update route.
router.put('/edit-form/:id', upload.single('picture'), async (req, res) => {
const id = req.params.id;
const title = req.body.title;
const gender = req.body.gender;
const brand = req.body.brand;
const description = req.body.description;
const price = req.body.price;
const image = req.file.filename;
try {
if (req.file) {
await sharp(req.file.path)
.resize(200, 200)
.jpeg({ quality: 90 })
.toFile(
path.resolve(req.file.destination, 'resized', image)
)
fs.unlinkSync(req.file.path)
Product.findOneAndUpdate(id,
{ $set: { title, gender, brand, description, price, image } },
{ new: true }
).then(post => {
res.redirect('/shop/products')
console.log(post)
})
.catch(err => {
return err;
});
}
} catch {
console.log('..')
}});
HTML:
<form action="/shop/edit-form/<%=product.id %>?_method=PUT" method="POST" enctype="multipart/form-data"> <!--Edit-form page to update a product-->
<label for="title">Title:</label>
<input type="text" class="form-control" placeholder="title" name="title" value="<%= product.title %>">
<label for="gender">Gender:</label>
<input type="text" class="form-control" placeholder="gender" name="gender" value="<%= product.gender%>">
<label for="brand">Brand:</label>
<input type="text" class="form-control" placeholder="brand" name="brand" value="<%= product.brand%>">
<label for="description">Description:</label>
<input type="text" class="form-control" placeholder="description" name="description" value="<%= product.description%>">
<label for="picture">Picture:</label>
<input type="file" class="form-control" placeholder="picture" name="picture" value="<%= product.picture%>">
<label for="price">Price:</label>
<input type="text" class="form-control" placeholder="price" name="price" value="<%= product.price%>">
<button class="btn btn-card" type="submit">Submit</button>
</form>