{"id":"3ea39a78825c6de4","repo":"mongodb/node-mongodb-native","slug":"file-not-found-for-id-id","errorCode":null,"errorMessage":"File not found for id ${id}","messagePattern":"File not found for id (.+?)","errorType":"exception","errorClass":"MongoRuntimeError","httpStatus":null,"severity":"error","filePath":"src/gridfs/index.ts","lineNumber":187,"sourceCode":"        serverSelectionTimeoutMS: this.s.db.client.s.options.serverSelectionTimeoutMS\n      });\n    }\n\n    const { deletedCount } = await this.s._filesCollection.deleteOne(\n      { _id: id },\n      { timeoutMS: timeoutContext?.remainingTimeMS }\n    );\n\n    const remainingTimeMS = timeoutContext?.remainingTimeMS;\n    if (remainingTimeMS != null && remainingTimeMS <= 0)\n      throw new MongoOperationTimeoutError(`Timed out after ${timeoutMS}ms`);\n    // Delete orphaned chunks before returning FileNotFound\n    await this.s._chunksCollection.deleteMany({ files_id: id }, { timeoutMS: remainingTimeMS });\n\n    if (deletedCount === 0) {\n      // TODO(NODE-3483): Replace with more appropriate error\n      // Consider creating new error MongoGridFSFileNotFoundError\n      throw new MongoRuntimeError(`File not found for id ${id}`);\n    }\n  }\n\n  /** Convenience wrapper around find on the files collection */\n  find(filter: Filter<GridFSFile> = {}, options: FindOptions = {}): FindCursor<GridFSFile> {\n    return this.s._filesCollection.find(filter, options);\n  }\n\n  /**\n   * Returns a readable stream (GridFSBucketReadStream) for streaming the\n   * file with the given name from GridFS. If there are multiple files with\n   * the same name, this will stream the most recent file with the given name\n   * (as determined by the `uploadDate` field). You can set the `revision`\n   * option to change this behavior.\n   */\n  openDownloadStreamByName(\n    filename: string,\n    options?: GridFSBucketReadStreamOptionsWithRevision","sourceCodeStart":169,"sourceCodeEnd":205,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/gridfs/index.ts#L169-L205","documentation":"Thrown by GridFSBucket.delete() when no file in the fs.files collection matches the supplied _id (deletedCount === 0). The driver wraps it as a MongoRuntimeError because GridFS lacks a dedicated 'file not found' error type (tracked as NODE-3483). It fires AFTER any orphaned chunks for that files_id are already cleaned up, so the bucket remains consistent. The id is interpolated into the message for diagnostics.","triggerScenarios":"Calling bucket.delete(id) with an ObjectId that was never uploaded, was already deleted, or belongs to a different bucket (different bucketName / database). Also triggered if the files collection was edited out-of-band or the wrong GridFSBucket instance is used.","commonSituations":"Deleting a file after it was already deleted; using an id fetched from a different environment/database; race conditions where another process deletes the file first; passing a string id instead of an ObjectId so the filter matches nothing.","solutions":["Verify the id exists before deleting, e.g. const file = await bucket.find({ _id: id }).next(); if (!file) return; then call bucket.delete(id).","Confirm you are using the same GridFSBucket instance (same db and bucketName) that uploaded the file.","Ensure id is an ObjectId, not a string: new ObjectId(id) when constructing the filter from a stored string.","Wrap the call in try/catch and treat MongoRuntimeError with this message as a benign no-op if idempotent deletion is intended."],"exampleFix":"// before\nawait bucket.delete(id); // throws if id absent\n\n// after\nconst existing = await bucket.find({ _id: id }, { limit: 1 }).next();\nif (existing) {\n  await bucket.delete(id);\n}","handlingStrategy":"validation","validationCode":"async function safeDelete(bucket, id) {\n  const exists = await bucket.find({ _id: id }, { limit: 1 }).hasNext();\n  if (!exists) return { deleted: false };\n  await bucket.delete(id);\n  return { deleted: true };\n}","typeGuard":"import { ObjectId } from 'mongodb';\nfunction isObjectId(v): v is ObjectId {\n  return v instanceof ObjectId;\n}","tryCatchPattern":"try {\n  await bucket.delete(id);\n} catch (e) {\n  if (e instanceof MongoRuntimeError && /File not found/.test(e.message)) return;\n  throw e;\n}","preventionTips":["Confirm id type is ObjectId before calling delete","Use one consistent GridFSBucket instance for upload and delete","Treat missing-file deletes as idempotent no-ops in cleanup paths"],"tags":["gridfs","file-not-found","delete"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}