如何将具有映射属性的基于结构的类型保存到MongoDB中

huangapple go评论84阅读模式
英文:

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

问题

我想将MongoDB用作会话存储,并将基于结构的数据类型保存到MongoDB中。

结构类型如下:

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

创建对Session结构类型的引用,并将一些数据放入属性中,例如:

type Authen struct {
    Name, Email string
}
a := &Authen{Name: "Foo", Email: "foo@example.com"}

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

如何将会话数据s保存到MongoDB中,并如何查询这些数据并再次保存到引用中?
我认为问题可能出现在类型为map[string]interface{}的数据属性上。

作为MongoDB的驱动程序,我将使用mgo

英文:

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: "foo@example.com"}

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

答案1

得分: 5

对于插入操作,没有什么特殊的要做。只需像通常一样将会话值插入数据库,地图类型将被正确插入:

err := collection.Insert(&session)

假设描述的结构,这将在数据库中插入以下文档:

{
  "id": "555555",
  "data": {
    "logged": {
      "name": "foo",
      "email": "foo@example.com"
    }
  }
}

然而,你不能像那样轻松地查询它,因为 map[string]interface{} 无法给 bson 包提供关于值类型的良好提示(它将最终成为一个地图,而不是 Authen)。为了解决这个问题,你需要在 Data 字段所使用的类型中实现 bson.Setter 接口。

英文:

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: "foo@example.com"}}}

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.

huangapple
  • 本文由 发表于 2015年3月5日 20:33:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/28877974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定