Search code examples
mongodbgomgo

Golang/mgo: Cannot retrieve value of int field from MongoDB document


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=9

It 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?


Solution

  • Have you tried setting the "key" value for that field?

    Unmarshal

    The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag.

    type Subscription struct {
        Id              bson.ObjectId    "_id,omitempty"
        Listen          string
        Job             string
        TimeoutSeconds  int     "TimeoutSeconds"
        Data            string
    }
    

    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.