Take a look at my custom update controller for clients, which updates the client’s data and their avatar photo. The old avatar gets deleted.
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
const _ = require('lodash');
module.exports = {
async update(ctx) {
//id of the client which I want to update
const { id } = ctx.params;
let entity;
//get the existing object of the client, if it doesnt exist then stop here.
let client = await strapi.services.clients.findOne({ id });
if (!client) {
return ctx.badRequest(`Client was not found.`);
}
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
//check if request constains any files
if (!_.isEmpty(files)) {
//if client has an existing avatar (otherwise it returns null)
if (client.avatar) {
//get the current avatar and delete it
const file = await strapi.plugins['upload'].services.upload.fetch({ id: client.avatar.id });
if (!file) {
return ctx.notFound('file.notFound');
}
await strapi.plugins['upload'].services.upload.remove(file);
}
//update the client with new data and avatar
entity = await strapi.services.clients.update({ id }, data, {
files,
});
} else {
//update client without files
entity = await strapi.services.clients.update({ id }, data);
}
} else {
entity = await strapi.services.clients.update({ id }, ctx.request.body);
}
return sanitizeEntity(entity, { model: strapi.models.clients });
},
};