Cannot get value "_id" using mgo with golang

This is my structure 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 from the database:

 func AllArticles() []Article { articles := []Article{} err := c_articles.Find(bson.M{}).All(&articles) if err != nil { panic(err) } return articles } 

This is one part of the object stored in the 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 cannot get the real value of the _id field, always "" . What is the problem?

+15
mongodb go mgo
Nov 26 '13 at 11:12
source share
3 answers

I found a problem.

In code:

 Id bson.ObjectId `json:"id" bson:"_id,omitempty"` 

between json: and bson: I used tab instead of space , so the problem arises. If I changed this line of code to:

 Id bson.ObjectId `json:"id" bson:"_id,omitempty"` 

With one space between json: and bson: it works very well.

+27
Dec 23 '13 at 8:10
source share

I had the same problem, and I was able to find out that my import was mixed up. I have a feeling that Gustavo could not reproduce the problem, because you did not include what looked like your import, and he filled them correctly.

Just to briefly explain how my problem was similar:

It -

 err := db.Find(bson.M{"_id": bson.ObjectIdHex(userId)}).One(&user) 

does not work for me, it will not receive information from the database and return it -

 {ObjectIdHex("") } 

How I fixed it ... we found that

On the server.go page, one of the imports was this one.

 "gopkg.in/mgo.v2" 

It must be this.

 "labix.org/v2/mgo" 

The real mistake is not in using gopkg.in/mgo.v2. The fact is that the code was moving import modules labix.org/ and gopkg.in.

So the trick is to use this.

 "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" 

Or that.

 "labix.org/v2/mgo" "labix.org/v2/mgo/bson" 

But do not mix them. The top is preferred as this is what the latest documents use.

Hope this helps.

+5
Apr 22 '15 at 15:15
source share

Your code is ok.

Here is a self-contained example that includes your unmodified code:

And here is the conclusion:

 "R\x94\xa4J\xff&\xc61\xc7\xfd%\xcc" "Some Title" 

The problem is elsewhere. For example, a collection may not have a _id field.

+3
Nov 26 '13 at 13:42 on
source share



All Articles