'UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'unlink' of undefined at Grid.remove

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,
    });
  }
};


Solution 1:[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();
  });
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Meilech