Missing fields when marshaling a struct with an inlined structs and Custom BSON Marshaling

61 views
Skip to first unread message

alco...@gmail.com

unread,
Jan 16, 2018, 6:51:27 AM1/16/18
to mgo-users
When marshaling a struct with an inline struct that has custom BSON marshaling, some of the fields in the "parent" struct don't get marshaled.

Here is the minimal code to reproduce the problem:

package main

import (
   
"fmt"
    "log"
   
"reflect"

   
"gopkg.in/mgo.v2/bson"
)

type
Person struct {
    Name string
}

func
(p *Person) GetBSON() (interface{}, error) {
   
return struct {
       
Name string
   
}{
        Name: p.Name,
   
}, nil
}

type
Student struct {
   
Person `bson:",inline"`
   
Course string
}

func main
() {
    s
:= &Student{
       
Person: Person{Name: "Alberto"},
        Course: "math",
    }

    bytes
, err := bson.Marshal(s)
    if err != nil {
        log
.Fatal("marshaling: ", err)
    }

    ss
:= &Student{}
    if err := bson.Unmarshal(bytes, ss); err != nil {
        log
.Fatal("unmarshaling: ", err)
    }

    if !reflect.DeepEqual(s, ss) {
        fmt
.Println("ERROR: students differ!")
        fmt
.Println(s)
        fmt
.Println(ss)
    } else {
        fmt
.Println("OK: students are the same!")
    }
}

The code above compares and student before and after marshal/unmarshal.  The student after the marshaling is missing the specific fields of the Student struct (i.e. "courses") and only has the fields in the inlined struct ("Person.Name").

If I comment out the "Person.GetBSON" method, the code works just fine, and the student is equal before and after the marshal/unmarshal.

Wha I'm doing wrong?

alco...@gmail.com

unread,
Jan 16, 2018, 7:47:29 AM1/16/18
to mgo-users
A few more comments:

- When I execute the code from the previous post, I get:
ERROR: students differ!
&{{Alberto} math}
&{{Alberto} }


- If I comment out the "Person.GetBSON" method and execute, I get the expected, correct, behaviour:
OK: students are the same!

- I'm using "gopkg.in/mgo.v2/bson" commit 3f83fa5005286a7fe593b055f0d7771a7dce4655 (Aug 17, 2016)

- i get the same results using "github.com/globalsign/mgo/bson" commit 896bbb89d21253a28cd5a7f8b81fe091410cb94d (Jan 15, 2018)
Reply all
Reply to author
Forward
0 new messages