node.jsmongodbgridfs

Problem deleting documents using GridFSBucket in MongoDB with Node.js


I'm working on a Node.js script where I'm using MongoDB as my database. I'm using GridFSBucket to handle documents in my database from mongodb library. I have three tables for that: document, document.chunks, and document.files.

I'm trying to delete specific documents using the bucket.delete(document._id) method, but I'm encountering an error that says: MongoRuntimeError: File not found for id

Here is the code I'm using:

const bucket = new GridFSBucket(db, { bucketName: "document" });
await bucket.delete(document._id);

I've confirmed that the document does exist in the database by using the findOne method from MongoDB, and it successfully retrieves the document. Here is the code I used:

const doc = await db.collection("document").findOne({
    _id: document._id,
});

This code works as expected and returns the correct document. However, when I try to delete the same document using the bucket.delete(document._id) method, it still throws the MongoRuntimeError: File not found for id

Has anyone experienced this problem before or have any idea how I can resolve it? Any help would be greatly appreciated.

Configuration:

  1. MongoDB: MongoDB 3.6.23 Community
  2. Database options:
 {
  enableUtf8Validation: true,
  forceServerObjectId: false,
  pkFactory: { createPk: [Function: createPk] },
  raw: false,
  readPreference: ReadPreference {
    mode: 'primary',
    tags: undefined,
    hedge: undefined,
    maxStalenessSeconds: undefined,
    minWireVersion: undefined
  },
  retryWrites: true
}
  1. Database read preference
 {
  mode: 'primary',
  tags: undefined,
  hedge: undefined,
  maxStalenessSeconds: undefined,
  minWireVersion: undefined
}
  1. Dependencies
  {
    "mongodb": "^6.3.0",
    "@types/node": "^20.11.16",
    "ts-node": "^10.9.2",
    "tslib": "^2.6.2",
    "uuid": "^9.0.1"
  }

Solution

  • I have managed to delete files through GridFS but instead of using the document identifier of the "document" collection as a parameter of the "delete" function I have had to first do a search in the bucket by filename and then also delete the document from the document table.

      const bucket = new GridFSBucket(db, { bucketName: "document" });
      const bucketFile = await bucket
        .find({
          filename: {
            $regex: `^${document._id.toString()}`,
          },
        })
        .toArray();
    
    const bucketFileId = bucketFile[0]._id;
      await bucket.delete(bucketFileId); //THIS DELETE DOCUMENTS FROM document.chunks COLLECTION AND DOCUMENT document.files COLLECTION
      const deleteResult = await db
        .collection("document")
        .deleteOne({ _id: document._id }); //THIS DELETE DOCUMENT FROM document COLLECTION