skip to Main Content

I’m trying to delete a file by its id using gridfs but I get this error when calling the delete API.

Controller :

let gfs;

connect.once("open", () => {
  gfs = Grid(connect.db, mongoose.mongo);
  gfs.collection("uploads");
});

exports.deleteFile = (req, res) => {
  try {
    gfs.remove(
      { _id: req.params.id, root: "uploads" },
      (err, gridStore) => {
        if (err) {
          return res.status(404).send({ message: err });
        } else {
          return res.send({ message: "File deleted successfuly" });
        }
      }
    );
  } catch (error) {
    return res.status(500).send({
      message: error.message,
    });
  }
};

2

Answers


  1. exports.deleteFileByFilename = async (req, res, next) => {
      const file = await gfs.files.findOne({ filename: req.params.filename });
      const gsfb = new mongoose.mongo.GridFSBucket(conn.db, { bucketName: 'uploads' });
      gsfb.delete(file._id, function (err, gridStore) {
        if (err) return next(err);
        res.status(200).end();
      });
    };
    
    Login or Signup to reply.
  2. // @route DELETE /files/:filename
    // @desc  Delete file
    
    app.delete('/files/:filename', async (req, res) => {
     
        const file = await gfs.files.findOne({ filename: req.params.filename });
        const gsfb = new mongoose.mongo.GridFSBucket(conn.db, { bucketName: 'uploads' });
        gsfb.delete(file._id, function (err, gridStore) {
            if (err) {
                res.status(404).send('no file found')
            }
            res.status(200).send('deleted successfully')
        });
    });
    

    On client side:

        const delImage = async (fileName) => {
        await axios.delete(`http://localhost:5000/files/${fileName}`);
        console.log('fileDeleted');
        getData(); // reminder to REFETCH the data so that database with deleted file is refreshed
    }
    

    I also made a video on this – full file uploads, multiupload, display and delete using MERN stack and NPM Multer thing, in here: https://youtu.be/4WT5nvfXcbs

    Docs for the video with full code: https://docs.google.com/document/d/1MxvNNc9WdJT54TpanpFBT6o7WE_7hPAmDhdRNWE8A9k/edit?usp=sharing

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search