You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go中更新MongoDB GridFS的Chunk数据?

MongoDB GridFS文件data字段更新问题求助

环境配置

主数据库名为node-craft,包含三个集合:node、Node-FileStorage.files和Node-FileStorage.chunks,各集合示例文档如下:

node集合

{
  "_id": { "$oid": "6526a1497d7b83889296939e" },
  "id": "2705973598",
  "name": "man_secretpassword.txt",
  "type": 1,
  "parentId": "2705952637",
  "directory": "/PROJECT/man_secretpassword.txt",
  "files": { "$oid": "6526a1497d7b83889296939c" }
}

Node-FileStorage.files集合

{
  "_id": { "$oid": "6526a1497d7b83889296939c" },
  "length": { "$numberLong": "27" },
  "chunkSize": 261120,
  "uploadDate": { "$date": "2023-10-11T13:21:13.309Z" },
  "filename": "man_secretpassword.txt"
}

Node-FileStorage.chunks集合

{
  "_id": { "$oid": "6526a1497d7b83889296939d" },
  "files_id": { "$oid": "6526a1497d7b83889296939c" },
  "n": 0,
  "data": {
    "$binary": {
      "base64": "bWFuQGdtYWlsLmNvbSAxMjM0IDAzMDkzMg0K",
      "subType": "00"
    }
  }
}

问题描述

我在使用MongoDB的GridFS存储文件时,无法更新文件的data字段。目前我有新内容字符串newContent以及chunks集合中的files_id,目标是更新该files_id对应的Chunk数据,并返回更新后的数据。尝试了多种方法都无效,求指导。

当前无效的更新函数

func UpdateGridFSChunk(chunkID string, newContent string) error {
    // Convert the new content string to bytes.
    newData := []byte(newContent)
    // Find the chunk by its ID.
    chunkObjID, err := primitive.ObjectIDFromHex(chunkID)
    if err != nil {
        return err
    }
    filter := bson.M{"_id": chunkObjID}
    chunkFileCursor, err := fs.Find(filter)
    if err != nil {
        return err
    }
    if chunkFileCursor.Next(context.Background()) {
        // Get the GridFS file properties.
        chunkFile := chunkFileCursor.File()
        // Create a new ObjectID for the updated chunk.
        newChunkObjID := primitive.NewObjectID()
        // Replace the chunk's data with the new data.
        err = fs.UploadFromStreamWithID(newChunkObjID, chunkFile.Filename, bytes.NewReader(newData))
        if err != nil {
            return err
        }
        err = fs.Delete(chunkObjID)
        if err != nil {
            return err
        }
    }
    return nil
}

内容的提问来源于stack exchange,提问作者Asim Altaf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:29:54