【发布时间】:2012-09-24 04:09:25
【问题描述】:
我有以下代码,但我不确定它为什么不返回 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(¬es)
if err != nil {
panic(iter.Err())
}
return notes
}
func main() {
notes := loadNotes()
for note := range notes {
fmt.Println(note.Title)
}
}
如果我只是打印出notes,我会得到看起来像是两个结构的切片,但我无法通过notes.Title 或类似的方式访问它们。
[{ Some example title 20 September 2012 Some example content}]
这是我的文档的样子:
> db.notes.find()
{ "_id" : "some-example-title", "title" : "Some example title", "date" : "20 September 2012", "body" : "Some example content" }
真正的问题是它将笔记作为一大片返回,而不是Note{}(我认为?)
如果我做的事情明显错误,任何见解都会有所帮助。
【问题讨论】:
-
^ 我让帖子更具描述性。