Question

I have a struct that contains math/big.Int fields. I would like to save the struct in mongodb using mgo. Saving the numbers as a strings is good enough in my situation.

I have looked at the available field's tags and nothing seams to allow custom serializer. I was expecting to implement an interface similar to encoding/json.Marshaler but I have found None of such interface in the documentation.

Here is a trivial example of what I want I need.

package main

import (
    "labix.org/v2/mgo"
    "math/big"
)

type Point struct {
    X, Y *big.Int
}

func main() {
    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()

    c := session.DB("test").C("test")
    err = c.Insert(&Point{big.NewInt(1), big.NewInt(1)})
    if err != nil { // should not panic
        panic(err)
    }

    //  The code run as expected but the fields X and Y are empty in mongo
}

Thnaks!

Was it helpful?

Solution

The similar interface is named bson.Getter:

It can look similar to this:

func (point *Point) GetBSON() (interface{}, error) {
    return bson.D{{"x", point.X.String()}, {"y", point.Y.String()}}, nil
}

And there's also the counterpart interface in the setter side, if you're interested:

For using it, note that the bson.Raw type provided as a parameter has an Unmarshal method, so you could have a type similar to:

type dbPoint struct {
    X string
    Y string
}

and unmarshal it conveniently:

var dbp dbPoint
err := raw.Unmarshal(&dbp)

and then use the dbp.X and dbp.Y strings to put the big ints back into the real (point *Point) being unmarshalled.

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