dqwr32867
2017-02-07 04:41
浏览 21

使用mongodb驱动程序和struct,用大写和小写查找混乱

var Messages []Token
c2 := session.DB("mydatabase").C("pages")
query2 := c2.Find(bson.M{}).All(&Messages)
fmt.Print(Messages)

Here's the structure in my Mongo DB:

id_
pageUrl
token
pageId

I first tried the structure as this:

type Token struct {
    PageUrl string
    Token string
    PageId string
}

but only the token was being printed, perhaps because it's all lowercase. The other two fields were not being retrieved because they contain uppercase. Then I tried this:

type Token struct {
    PageUrl string `json: "pageUrl" bson: "pageUrl"`
    Token string `json: "token" bson: "token"`
    PageId string `json: "pageId" bson: "pageId"`
}    

what are those bson and json things? I've only put it there because I've seen in the internet, but it doesn't work, I still get only the token field

UPDATE with solution and tested example for nested documents

I've seen that there was no posts regarding this question so remember that the solution was to remove the spaces between json: and bson: Also, to help someone who might be wondering how to do it for nested structs, here I give two structures that worked for me:

type Token struct {
    PageUrl string `json:"pageUrl" bson:"pageUrl"`
    Token string `json:"token" bson:"token"`
    PageId string `json:"pageId" bson:"pageId"`
}


type Message struct {
    Sender struct {
        Id string `json:"id" bson:"id"`
    } `json:"sender" bson:"sender"`
    Recipient struct {
        Id string `json:"id" bson:"id"`
    } `json:"recipient" bson:"recipient"`
    Message struct {
        Mid string `json:"mid" bson:"mid"`
        Seq int `json:"seq" bson:"seq"`
        Message string `json:"text" bson:"text"`
    }
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshang6062 2017-02-07 06:39
    已采纳

    these json and bson stuff is called tags

    My best guess is that because Go requires a variable or function to be public by Capitalize the first character, so serialize frameworks like json or bson require the struct Capitalize its first character to expose the field(so that it could see the field). Thus the exposed field name should be defined with a tag (to avoid the restriction).

    the space between bson: and "token" seems to have cause the problem

    I tried following code snippet and seems works fine.

    type Token struct {
        PageUrl string `json:"pageUrl" bson:"pageUrl"`
        Token string `json:"token" bson:"token"`
        PageId string `json:"pageId" bson:"pageId"`
    } 
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题