bson.M构建

I have a fairly odd question that I have been trying to wrap my head around and am looking of some pointers as to the best approach. I am use mgo to filter a collection that contains a few different types of structs and am trying to cast from bson.M to the proper struct after the fact. Basically I'd like to be able to filter the collection and look at each result and based on a common field cast to the proper struct.

Here is sample of the structs I am trying to use.

  type Action interface {
    MyFunc() bool
  }

  type Struct1 struct {
    Id bson.ObjectId `bson:"_id,omitempty"`
    Type  string `bson:"type"`
    Struct1Only string `bson:"struct1only"`
  }

  func (s Struct1) MyFunc() bool {
    return true
  }

  type Struct2 struct {
    Id bson.ObjectId `bson:"_id,omitempty"`
    Type string `bson:"type"`
    Struct2Only string `bson:"struct2only"`
  }

  func (s Struct2) MyFunc() bool {
    return true
  }

My initial idea was to do something like:

var result bson.M{}
err := c.Find(bson.M{nil}).One(&result)

Then switch on the type field and cast to the proper struct, but honestly I am new to go and mongo and am sure there is better way to do this. Any suggestions? Thanks

drdl18946
drdl18946 我已经简化了示例的结构,在我的项目中,它们之间有大约10个字段,它们实际上共享大约15个字段。我可以组合这些结构,只是有几个根据类型而为零的字段,我只是想将结构分开,因为我认为这样会更干净。
4 年多之前 回复
dongxin0031
dongxin0031 此外,也就是说,如果两个结构在一个字段中只是不同,则可以并且可能应该将它们组合。不存在的字段仅求值为nil。
4 年多之前 回复
doufu1504
doufu1504 您要将两种不同的结构类型存储到一个集合中?我不知道有任何方法可以猜测正确的方法,以将结果强制转换为结果,而无需显式打开特定于任一结构的字段。
4 年多之前 回复

1个回答

You don't have to convert bson.M to struct, instead, you directly pass a struct pointer to the One function

var struct2 Struct2
err := c.Find(bson.M{nil}).One(&struct2)

In case of you still want to convert bson.M to struct, use Marshal and Unmarshal

var m bson.M
var s Struct1

// convert m to s
bsonBytes, _ := bson.Marshal(m)
bson.Unmarshal(bsonBytes, &s)
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问