Search code examples
javascriptgridfsgridfs-stream

MongoDB Gridfs-stream is Only Deleting the File but Not the Chunk


I am trying to delete a file and chunk from my MongoDB database but my route only deletes the file but not the chunk. I've seen a few StackOverflow solutions to this issue but they are either now outdated or are based on the deprecated remove() function. I saw another solution that claimed that adding root: bucketName to the delete query options fixes this issue, but it didn't for me.

const router = require("express").Router();
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = require("mongodb").ObjectId;
const { authUser } = require("../middleware/auth");
const uploadMulter = require("../middleware/upload");
const Grid = require("gridfs-stream");

const connection = mongoose.connection;

let gfs, gridfsBucket;

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

router.delete("/files/:_id", (req, res) => {

  gfs
    .collection("profilePictures")
    .deleteOne({ _id: ObjectId(req.params._id) }, (err) => {});//only deletes the profilePicture.file, but not profilePicture.chunk
});


Solution

  • I found that using delete() removes both the chunk and file but it must be ran on the gridfsBucket. All other "solutions" on StackOverflow use either the deprecated remove() or deleteOne()on gfs.

    The issue with this solution is that the delete() function only works with BSON _id's so If you would like to delete files based on filename or metadata then It wont work.

    router.delete("/files/:_id", (req, res) => {
      gridfsBucket = new mongoose.mongo.GridFSBucket(connection.db, {
        bucketName: "profilePictures",
      });
      gridfsBucket.delete(ObjectId(req.params._id));
    });