How to delete image associated with a document in mongodb using s3 bucket?

I am saving user data with their image and for storage, I am using s3 bucket of aws. In my upload API, I am saving the URL of the image in the database. I want to implement that if I delete the user the image also be deleted from the s3 bucket. I wrote the delete API too but I need some guidance on how to use it? here is my s3 delete API code.

delete a file from s3

function deleteFileStream(fileKey, next) {
    const deleteParams = {
        Key: fileKey,
        Bucket: bucket_name,
    }
    s3.deleteObject(deleteParams, (error, data) => {
        next(error, data)
    })
}
exports.deleteFileStream = deleteFileStream;

my router controller

router.delete("/deleteImage/:key", (req, res) => {
    const key = req.params.key
    deleteFileStream(key, (error, data) => {
        if (error) {
            return res.send({ error: "Can not delete file, Please try again later" });
        }
        return res.send({ message: "File has been deleted successfully" });
    });
})

those apis are working fine in postman. I need some guidance on how to use it in my delete user route so that if I delete a user the image associated with also deleted from my s3 bucket.

my delete user API

function user_delete(req, res) {
    User.findByIdAndRemove(req.params.id)
        .then(data => {
            if (!data) {
                return res.status(404).send({
                    success: false,
                    message: "User not found with id " + req.params.id
                });
            }
            res.send({
                success: true,
                message: "User successfully deleted!"
            });
        })
};
router.delete('/delete/:id', deleteUser);

Hi :wave: @Naila_Nosheen,

Welcome to the MongoDB Community forums :sparkles:

The userModel I’m assuming here:

{
_id: ObjectId(...),
userName: "Naila_Nosheen",
imageURL: "https://s3.us-west-2.amazonaws.com/mybucket/image01.jpg",
...
}

I’d suggest you call the deleteFileStream function within the user_delete function and pass the keyName as the parameter before deleting the user from the DB then using the multiple promises you can delete both.

I’m putting up the rough code snippet (for reference) :point_down:

var path = require("path")

function user_delete(req, res) {
    const user = User.findById(req.params.id);
    const keyName = path.basename(user.imageURL)

    // var user.imageURL = "https://s3.us-west-2.amazonaws.com/mybucket/image01.jpg"
    // const keyName = path.basename(user.imageURL) // "image01.jpg"

    //Deleting the user from the DB
    User.findByIdAndRemove(req.params.id)
        .then(data => {
            if (!data) {
                return res.status(404).send({
                    success: false,
                    message: "User not found with id " + req.params.id
                });
            }
        }).then(() => {
            //Deleting the Image from the S3 bucket
            deleteFileStream(keyName, (error, data) => {
                if (error) {
                    return res.status(500).send({
                        success: false,
                        message: error.message
                    });
                } 
                res.send({
                    success: true,
                    message: "<Message>"
                });
            })
        })
};

Note that this is an untested example and may not work in all cases. Please do the test any code thoroughly with your use case so that there are no surprises.

I hope it answers your questions. Please let us know if you have any follow-up questions.

Thanks,
Kushagra

3 Likes

Thank you for the answer. @Kushagra_Kesav It worked now if I delete user its image also deleted. can you please help me on one thing too? i have image data also in child model. And I want to implement if I delete user the child also deleted with its data image on server. I user remove middleware for cascade delete and it is working fine. On deleting parent(User) the child also deleted but its image not deleting. here is the link to my code example How to delete data from child and also its image data on server if we delete parent in nodejs mongodb

Hi @Naila_Nosheen,

I’m glad to know that it worked and it got resolved.

To better understand the other issue, could you please provide the user model in this thread.

Thanks,
Kushagra

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.