Search code examples
gomgo

How to save struct based type with a map property into mongodb


I want to use mongodb as session storage and save a struct based data type into mongodb.

The struct type looks like:

type Session struct {
    Id  string
    Data map[string]interface{}
}

And create reference to Session struct type and put some data into properties like:

type Authen struct {
    Name, Email string
}
a := &Authen{Name: "Foo", Email: "[email protected]"}

s := &Session{}
s.Id = "555555"
s.Data["logged"] = a

How to save the session data s into mongodb and how to query those data back and save into a reference again? I think the problem can occurs with the data property of type map[string]interface{}.

As driver to mongodb I would use mgo


Solution

  • There's nothing special to be done for inserts. Just insert that session value into the database as usual, and the map type will be properly inserted:

    err := collection.Insert(&session)
    

    Assuming the structure described, this will insert the following document into the database:

    {id: "555555", data: {logged: {name: "foo", email: "[email protected]"}}}
    

    You cannot easily query it back like that, though, because the map[string]interface{} does not give the bson package a good hint about what the value type is (it'll end up as a map, instead of Authen). To workaround this, you'd need to implement the bson.Setter interface in the type used by the Data field.