Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bson.M to struct

Tags:

mongodb

go

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

like image 985
ShootThePuck91 Avatar asked Apr 01 '16 17:04

ShootThePuck91


1 Answers

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)
like image 82
thanhpk Avatar answered Oct 19 '22 05:10

thanhpk