This is my struct definition:
type Article struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Title string `json:"title"`
Author string `json:"author"`
Date string `json:"date"`
Tags string `json:"tags"`
Content string `json:"content"`
Status string `json:"status"`
}
This is the method I get my data from database:
func AllArticles() []Article {
articles := []Article{}
err := c_articles.Find(bson.M{}).All(&articles)
if err != nil {
panic(err)
}
return articles
}
This is one piece of object stored in database:
{ "_id" : ObjectId( "5281b83afbb7f35cb62d0834" ),
"title" : "Hello1",
"author" : "DYZ",
"date" : "2013-11-10",
"tags" : "abc",
"content" : "This is another content.",
"status" : "published" }
This is the printed result:
[{ObjectIdHex("") Hello1 DYZ 2013-11-10 abc This is another content. published} {ObjectIdHex("") Hello2 DYZ 2013-11-14 abc This is the content. published}]
It seems that I can't get the real value of _id
field, it's always ""
. What's the problem?
I've found the problem.
In the code:
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
between json:
and bson:
, I used a tab
instead of space
so the problem occurs. If I change this line of code to:
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
With one space
between json:
and bson:
, it turns out to work just fine.