【问题标题】:Golang - MongoDB (mgo) retrieve inserted file (BSON not GridFS)Golang - MongoDB (mgo) 检索插入的文件(BSON 不是 GridFS)
【发布时间】:2015-07-21 05:36:34
【问题描述】:

我是 Golang 的新手。 我正在尝试检索已插入的 PDF 文件对象。我没有使用 GridFS,因为我要存储的文件小于 16 MB。 对象已被插入(使用 load_file 函数),我在 MongoDB 可视客户端中看到的对象 ID 是 ObjectId("554f98a400afc2dd3cbfb21b")。

不幸的是,在磁盘上创建的文件为 0 kb。 请告知如何正确检索插入的 PDF 对象。

谢谢

package main

import (
    "fmt"
    "io/ioutil"

    "gopkg.in/mgo.v2"
)

type Raw struct {
    Kind byte
    Data []byte
}

type RawDocElem struct {
    Name  string
    Value Raw
}

func check(err error) {
    if err != nil {
        panic(err.Error())
    }
}

func read_file_content(AFileName string) []byte {

    file_contents, err := ioutil.ReadFile(AFileName)
    check(err)
    return file_contents
}

func save_fetched_file(AFileName RawDocElem) {
    ioutil.WriteFile("fisier.pdf", AFileName.Value.Data, 0644)
    fmt.Println("FileName:", AFileName.Name)
}

func load_file(AFileName string, ADatabaseName string, ACollection string) {
    session, err := mgo.Dial("127.0.0.1,127.0.0.1")

    if err != nil {
        panic(err)
    }
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)

    c := session.DB(ADatabaseName).C(ACollection)

    the_obj_to_insert := Raw{Kind: 0x00, Data: read_file_content(AFileName)}

    err = c.Database.C(ACollection).Insert(&the_obj_to_insert)
    check(err)

}

func get_file(ADatabaseName string, ACollection string, The_ID string) RawDocElem {
    session, err := mgo.Dial("127.0.0.1,127.0.0.1")

    if err != nil {
        panic(err)
    }
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)
    c := session.DB(ADatabaseName).C(ACollection)

    result := RawDocElem{}
    err = c.FindId(The_ID).One(&result)
    return result
}

func main() {
    //f_name := "Shortcuts.pdf"
    db_name := "teste"
    the_collection := "ColectiaDeFisiere"
    //load_file(f_name, db_name, the_collection)
    fmt.Sprintf(`ObjectIdHex("%x")`, string("554f98a400afc2dd3cbfb21b"))
    save_fetched_file(get_file(db_name, the_collection, fmt.Sprintf(`ObjectIdHex("%x")`, string("554f98a400afc2dd3cbfb21b"))))
}

【问题讨论】:

  • 我更改了两项: objectID := bson.ObjectIdHex(The_ID) 加上 err = c.FindId(objectID).One(&result) 和 b.返回的对象是 Raw 类型,而不是 RawDocElem。在此之后它正确保存了pdf。

标签: mongodb go


【解决方案1】:

我认为您构建对象 ID 的方式是错误的。此外,您忘记在 FindId 调用之后测试错误。

我会尝试导入 bson 包,并使用以下内容构建对象 ID:

hexString := "554f98a400afc2dd3cbfb21b" //24 digits hexadecimal string
objid := bson.ObjectIdHex(hexString)
...
err = c.FindId(objid).One(&result)
if err == nil {
   // Do something with result
   ...
} else {
   // Error
   ...
}

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 2018-04-16
    • 1970-01-01
    • 2018-07-28
    • 2014-04-28
    • 2015-12-30
    • 2016-01-01
    • 2015-09-27
    • 1970-01-01
    相关资源
    最近更新 更多