Cannot retrieve “_id” value using mgo with golang

前端 未结 3 1046
無奈伤痛
無奈伤痛 2021-01-07 18:14

This is my struct definition:

type Article struct {
    Id      bson.ObjectId `json:\"id\"        bson:\"_id,omitempty\"`
    Title   string        `json:\"t         


        
相关标签:
3条回答
  • 2021-01-07 18:48

    I had the same issue and was able to figure out that I had my imports mixed up. I have a feeling that Gustavo could not reproduce the problem because you had not included what your imports looked like and he filled them out correctly.

    Just to explain briefly how my issue was similar:

    This -

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

    was not working for me, it would not get the info from the database and would return this-

    {ObjectIdHex("")    }
    

    How I fixed it...we found that

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

    "gopkg.in/mgo.v2”
    

    Should have been this.

    "labix.org/v2/mgo”
    

    The real bug is not the use of the gopkg.in/mgo.v2. It is that the code was mixing labix.org/ and gopkg.in import modules.

    So the trick is to use this.

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

    Or this.

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

    But not mix them. The top one is the preferred one, as that is what the latest docs use.

    Hope this helps.

    0 讨论(0)
  • 2021-01-07 18:49

    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.

    0 讨论(0)
  • 2021-01-07 18:51

    Your code is fine.

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

    • http://play.golang.org/p/7C9roLtL0f

    And here is the output:

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

    The issue is elsewhere. The collection may really not have an _id field, for example.

    0 讨论(0)
提交回复
热议问题