In the front-end use form-data to send a post/put method to save data and edit data in the server. In the front-end have a problem with the image field. when new data is added. the new data will be saved. but when they try to edit data, the data changes made will not be saved, only saved if the image field is changed. (this problem only occurs in ios). in IOS when they try to update data without changing the image field server will be crashed
router.put("/:id", authenticate, async (req, res) => {
uploads(req, res, function (err) {
if (err instanceof multer.MulterError) {
return send(res, RESPONSE.FILE_TOO_LARGE);
} else if (err) {
return send(res, RESPONSE.UNKNOWN_ERROR);
}
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: `uploads/${uuid()}`,
Body: req.file.buffer,
};
s3.upload(params, async (error, data) => {
if (error) {
send(res, RESPONSE.UNKNOWN_ERROR);
}
try {
const id = req.params.id;
const updatedData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
phone: req.body.phone,
email: req.body.email,
image: data.Key,
};
const options = { new: true };
await SomeModel.findByIdAndUpdate(id.trim(), updatedData, options);
return send(res, RESPONSE.SUCCESS);
} catch (err) {
return res.status(400).send(err.message);
}
});
CodePudding user response:
Sounds like you should only do the S3 upload and set image
if req.file
is present
router.put("/:id", authenticate, (req, res) => {
uploads(req, res, async (err) => {
if (err instanceof multer.MulterError) {
return send(res, RESPONSE.FILE_TOO_LARGE);
} else if (err) {
return send(res, RESPONSE.UNKNOWN_ERROR);
}
const id = req.params.id;
const updatedData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
phone: req.body.phone,
email: req.body.email,
};
try {
if (req.file) {
const { Key } = await s3
.upload({
Bucket: process.env.AWS_BUCKET_NAME,
Key: `uploads/${uuid()}`,
Body: req.file.buffer,
})
.promise();
updatedData.image = Key;
}
await SomeModel.findByIdAndUpdate(id.trim(), updatedData, { new: true });
return send(res, RESPONSE.SUCCESS);
} catch (err) {
return res.status(400).send(err.message);
}
});
});