Empty Objects in MongoDB Queries with Go
While learning Go API development, you may encounter issues retrieving data from MongoDB using the mgo package. One such issue is obtaining empty objects when performing queries. To resolve this, it's essential to understand the use of BSON and JSON tags in the Go struct.
In your provided code, the issue arises because the fields in the users struct are not exported or tagged. Therefore, they are ignored by the mgo package. To fix this, you need to export the fields by capitalizing the first letters, like:
type Users struct { User string `bson:"user" json:"user"` Data string `bson:"data" json:"data"` }
By default, the field name is assumed when transforming struct values to/from MongoDB. However, tags allow you to map fields to specific names for serialization and retrieval. In this case, you've defined tags to match the BSON and JSON field names.
After these changes, your code will successfully retrieve non-empty objects from the MongoDB collection. The print line will display the correct user data and the count of messages in the collection.
The above is the detailed content of Why Am I Getting Empty Objects When Querying MongoDB with Go?. For more information, please follow other related articles on the PHP Chinese website!