3

I am trying to decode a struct which contains a result field, where the result field is either a null or string value. I'm trying to decode this into a string pointer but I get the error:

type MyStruct struct {
    Result   *string `json:"result,omitempty" bson:"result"`
}

The bson/json is something like:

{"result" : null}

or

{"result" : "somedata"}

Decode with:

var result MyStruct

err := collection.FindOne(ctx, filter).Decode(&result)
if err != nil {
    s.logFile.Fatal(err)
}

Error:

cannot decode null into a string type

I'm using the official driver: "github.com/mongodb/mongo-go-driver/mongo" & "github.com/mongodb/mongo-go-driver/x/bsonx"

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
mbudge
  • 557
  • 13
  • 28
  • Far better is avoid null. Empty string is better than pointer. – Alex Pliutau Nov 21 '18 at 15:07
  • Your code should work rightfully. It looks the unmarshaling process is not the reverse of the marshaling process. The official MongoDB driver is in **alpha** phase. Report this at their site and hope they make this work sometime in the future. – icza Nov 21 '18 at 15:31
  • Why are you traying to have point to stirng. I think your problem may solve if you use Result string – Ehsan.Saradar Nov 21 '18 at 16:06
  • 1
    I'm parsing data from another teams mongodb, and I think they do it because the value wasn't set, instead of it being set but empty. I'll make a ticket on the mongo driver GitHub. Thanks – mbudge Nov 21 '18 at 16:18
  • 1
    You can try like this https://play.golang.org/p/K6Nlhg3LN5W. – Shudipta Sharma Nov 21 '18 at 17:47
  • do you have a link to the ticket? – robbmj Dec 19 '18 at 15:43

0 Answers0