4

I have a GOLANG struct as follows:

type OrgWhoAmI struct {
FriendlyName            string        `json:"friendlyName"`
RedemptionCode          string        `json:"redemptionCode"`
StartUrls               []StartUrl    `json:"startUrls"`
Status                  string        `json:"status"`
Children                []OrgChildren `json:"childrenReemptionCodes"`
}

type StartUrl struct {
DisplayName string `json:"displayName"`
URL         string `json:"url"`
}

type OrgChildren struct {
FriendlyName   string `json:"childFriendlyName"`
RedemptionCode string `json:"childRedemptionCode"`
}

I've created and successfully inserted records into a MongoDB collection (as I can see the results by querying Mongo with the CLI mongo program) - but when I query with MGO as follows, I get nothing:

func main() {
    session, sessionErr := mgo.Dial("localhost")
defer session.Close()

    // Query All
    collection := session.DB("OrgData").C("orgWhoAmI")
var results []OrgWhoAmI
err = collection.Find(bson.M{}).All(&results)
if err != nil {
    panic(err)
}
for _, res := range results {
    fmt.Printf("Result: %s|%s\n", res.FriendlyName, res.RedemptionCode)
}
}

The results printed are:

Result: | Result: | Result: | Result: |

If I ask for the count for records, I get the correct number, but all values for all fields are blank. Not sure what I'm missing here.

4

1 回答 1

7

如果你没有在 go 中创建它们,它可能没有为你正确地序列化键名。bson 的默认值是小写键,所以如果你想要别的东西,你需要指定它。另请注意,您有一个拼写错误OrgWhoAmIjson:"childrenReemptionCodes"我猜应该是 Redemption)。如果您希望它们不同,可以分别指定 bson 和 json。

type OrgWhoAmI struct {
   FriendlyName            string        `bson:"friendlyName" json:"friendlyName"`
   RedemptionCode          string        `bson:"redemptionCode" json:"redemptionCode"`
   StartUrls               []StartUrl    `bson:"startUrls" json:"startUrls"`
   Status                  string        `bson:"status" json:"status"`
   Children                []OrgChildren `bson:"childrenRedemptionCodes" json:"childrenRedemptionCodes"`
}

type StartUrl struct {
   DisplayName string `bson:"displayName" json:"displayName"`
   URL         string `bson:"url" json:"url"`
}

type OrgChildren struct {
   FriendlyName   string `bson:"childFriendlyName" json:"childFriendlyName"`
   RedemptionCode string `bson:"childRedemptionCode" json:"childRedemptionCode"`
}
于 2014-01-02T19:15:13.063 回答