這是我的結構體:
type Article struct {
Id bson.ObjectId `json:"id" bson:"_id"`
Title string `json:"title"`
Author string `json:"author"`
Date string `json:"date"`
Tags string `json:"tags"`
Content string `json:"content"`
Status string `json:"status"`
}
這是我獲取 mongodb 中數據的函數:
func AllArticles() []Article {
articles := []Article{}
err := c_articles.Find(bson.M{}).All(&articles)
if err != nil {
panic(err)
}
fmt.Println(articles)
return articles
}
這是打印結果:
[{ObjectIdHex("") Hello1 DYZ 2013-11-10 abc This is another content. published} {ObjectIdHex("") Hello2 DYZ 2013-11-14 abc This is the content. published} {ObjectIdHex("") Hello3 DYZ 2013-11-15 abc This is the content haven't been published. draft}]
可以看到,對應_id
的值是ObjectIdHex("")
,但是在數據庫中的數據是這樣的:
{ "_id" : ObjectId("5281b83afbb7f35cb62d0834"), "title" : "Hello1", "author" : "DYZ", "date" : "2013-11-10", "tags" : "abc", "content" : "This is another content.", "status" : "published" }
即使我把篩選條件變成:
err := c_articles.Find(bson.M{"_id": bson.ObjectIdHex("5281b83afbb7f35cb62d0834")}).All(&articles)
打印出來的數據仍然是上麵那樣,沒有值。這是為什麼?
Id bson.ObjectId
json:"id" bson:"_id"
json和bson之間的空格是否用了tab?