Remove orphaned images node app

Remove orphaned images node app
0

#1

I have a post request in which the user can go to their profile pic page and upload a picture. I am using multer and express to upload the images. Everything works fine, the image is uploaded, entered into my local mongoose database.

The problem is that since it’s a post request, the images keep on adding both in database and the disk. Following is my code:

// Update profile picture
router.post('/profilepic', ensureAuthenticated, (req, res) => {
    upload(req, res, (err) => {
        if (err) {
            res.render('user/userdashboard', {
                error_msg: err
            });
        } else {
            if (req.file == undefined) {
                res.render('user/profilepic', {
                    error_msg: 'Error: No file selected! you must select a file to upload'
                });
            } else {
                let thumbImageName = 'profilethumb_' + req.file.filename;
                const newImage = {
                    profile_pic: req.file.filename,
                    member_id: req.user.member_id,
                    imagePath: req.file.destination,
                    imagePath2: req.file.path,
                    imageSizebytes: req.file.size,
                    imageThumb: thumbImageName
                }
                new Image(newImage)
                    .save();
                req.flash('success_msg', 'Image saved.');
                res.redirect('/user/userdashboard');
            }
        }
    });

});

I am storing the destination and path in the database as well, so what I want to achieve is that when a user uploads a new profile image, the previous image on disk as well as in the db is removed/Deleted so that no matter how many times the profile picture is uploaded, only one copy is maintained for the user and that is the most recently uploaded one. Thanks in advance guys for any help.