Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
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
});

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!