使用 Go 检索 MongoDB 文档的问题

Zen*_*Zen 3 go mongodb mgo

我有以下代码,但我不确定为什么它不返回 Notes 的一部分。我正在使用 labix.org 的 mgo 库连接到 MongoDB 并遵循他们的在线文档。

type Note struct {
    Url string
    Title string
    Date string
    Body string
}

func loadNotes() ([]Note) {
    session, err := mgo.Dial("localhost")
    if err != nil {
            panic(err)
    }
    defer session.Close()

    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("test").C("notes")

    notes := []Note{}
    iter := c.Find(nil).Limit(100).Iter()
    err = iter.All(&notes)
    if err != nil {
        panic(iter.Err())
    }

    return notes
}

func main() {
    notes := loadNotes()
    for note := range notes {
        fmt.Println(note.Title)
    }
}  
Run Code Online (Sandbox Code Playgroud)

如果我只是打印出来,notes我会得到看起来像两个结构体的切片,但我无法通过notes.Title或类似的方式访问它们。

[{ Some example title 20 September 2012 Some example content}]
Run Code Online (Sandbox Code Playgroud)

这是我的文件的样子:

> db.notes.find()
{ "_id" : "some-example-title", "title" : "Some example title", "date" : "20 September 2012", "body" : "Some example content" }
Run Code Online (Sandbox Code Playgroud)

真正的问题是它将笔记作为一大片而不是Note{}(我认为?)

如果我做的事情明显是错误的,任何见解都会有所帮助。

jor*_*lli 5

你的问题在这里:

for note := range notes {
    fmt.Println(note.Title)
}
Run Code Online (Sandbox Code Playgroud)

它应该是:

for _, note := range notes {
    fmt.Println(note.Title)
}
Run Code Online (Sandbox Code Playgroud)

在切片上使用 range 语句返回形式为 的对i, v,其中 i 是切片中的索引, v 是该切片中索引处的项目。由于您省略了第二个值,因此您是在索引上循环,而不是在Note值上循环。

它位于规范的 RangeClause 部分:http ://golang.org/ref/spec#RangeClause