我正在查询一个包含其值中的整数值的集合,并将结果文档加载到此结构中:
type Subscription struct { Id bson.ObjectId "_id,omitempty" Listen string Job string TimeoutSeconds int Data string } var subscription Subscription subscriptions := subscriptionsCol.Find(bson.M{"listen": "example_channel"}).Iter() for subscriptions.Next(&subscription) { log("Pending job: %s?%s (timeout: %d)\n", subscription.Job, subscription.Data, subscription.TimeoutSeconds) }这是phpMoAdmin向我展示的内容:
[_id] => MongoId Object ( [$id] => 502ed8d84eaead30a1351ea7 ) [job] => partus_test_job_a [TimeoutSeconds] => 30 [listen] => partus.test [data] => a=1&b=9令我感到困惑的是, subscription.TimeoutSeconds总是包含0,当我肯定时,我在文档中插入了30 。
检索所有其他值即可。
int类型有什么问题?
I am querying a collection that includes an integer value among it's values, and loading resulting documents into this struct:
type Subscription struct { Id bson.ObjectId "_id,omitempty" Listen string Job string TimeoutSeconds int Data string } var subscription Subscription subscriptions := subscriptionsCol.Find(bson.M{"listen": "example_channel"}).Iter() for subscriptions.Next(&subscription) { log("Pending job: %s?%s (timeout: %d)\n", subscription.Job, subscription.Data, subscription.TimeoutSeconds) }This is what phpMoAdmin shows me:
[_id] => MongoId Object ( [$id] => 502ed8d84eaead30a1351ea7 ) [job] => partus_test_job_a [TimeoutSeconds] => 30 [listen] => partus.test [data] => a=1&b=9It puzzles me that subscription.TimeoutSeconds contains always 0, when I'm positive I have 30 in the document I inserted in the collection.
All other values are retrieved OK.
What's wrong with the int type?
最满意答案
您是否尝试过为该字段设置“密钥”值?
解组
type Subscription struct { Id bson.ObjectId "_id,omitempty" Listen string Job string TimeoutSeconds int "TimeoutSeconds" Data string }小写字段名称用作每个导出字段的键,但可以使用相应的字段标记更改此行为。
其他字段工作正常,因为它们的小写值与集合中的Mongo字段匹配,而TimeoutSeconds正在使用TitleCase。 发生的事情是int字段被保留为零值,因为Unmarshal无法将字段映射到它。
Have you tried setting the "key" value for that field?
Unmarshal
type Subscription struct { Id bson.ObjectId "_id,omitempty" Listen string Job string TimeoutSeconds int "TimeoutSeconds" Data string }The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag.
The other fields are working fine because their lowercase value matches your Mongo fields in the collection, whereas TimeoutSeconds is using the TitleCase. What is happening is the int field is being left at its zero value, since the Unmarshal can't map a field to it.
更多推荐
发布评论