Go mgo: Empty Objects Retrieval
When attempting to retrieve objects from a MongoDB instance using the Go mgo package, it's possible to encounter empty result objects. This issue can stem from improper field handling in the structs used to represent the MongoDB documents.
In your code sample, you define a users struct with the following fields:
type users struct { user string `bson:"user" json:"user"` data string }
However, the fields are not exported (uppercase first letter). Accordingly, the mgo package ignores them during serialization and deserialization with MongoDB. To fix this, export the fields:
type users struct { User string `bson:"user" json:"user"` Data string `bson:"data" json:"data"` }
By exporting the fields (using uppercase first letters), the mgo package can now recognize them and map them to the corresponding MongoDB fields. As a reminder, by default, the field names in the struct are used for mapping. To specify custom mapping, use tags (such as bson and json in the example).
The above is the detailed content of Why are my Go mgo queries returning empty objects?. For more information, please follow other related articles on the PHP Chinese website!