Question

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?

Was it helpful?

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.

OTHER TIPS

When UnMarshalling data, there are multiple keys that are supported. Below are some examples:

type T struct {
    A bool
    B int    "myb"
    C string "myc,omitempty"
    D string `bson:",omitempty" json:"jsonkey"`
    E int64  ",minsize"
    F int64  "myf,omitempty,minsize"
}

The general spec for 1 key-value pair during marshal is :

"[<key>][,<flag1>[,<flag2>]]"

`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)` 

GO provides support for particular keywords like bson (for mongo keys) and json for setting the json key in a resposne.

Check the Marshal GO Reference for more information.

Similarly there are some frameworks which provide further options to define the keys befor parsing. For example, in sql jinzhu github library gives support for setting default values, column ids to map, etc.

Anyone can use this feature and provide customized support.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top