Golang / mgo: leave blank fields from insert

For some reason, mgo

inserts an empty structure into db as null, even though I set the omitempty option.

package main

import (
    "fmt"
    "encoding/json"
)

type A struct {
    A bool
}

type B struct {
    X       int `json:"x,omitempty" bson:"x,omitempty"`
    SomeA   *A `json:"a,omitempty" bson:"a,omitempty"`
}

func main() {
    b := B{}
    b.X = 123

    if buf, err := json.MarshalIndent(&b, "", " "); err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(string(buf))
    }
}

      

The json encoder leaves the property SomeA

, but it resides in the database as "a" : null

. Am I doing something wrong, or is it just not possible to do it this way?

+3


source to share


1 answer


Yes, so the problem was there were tabs between the json and bson encoder settings, so idle didn't work. So this is wrong :

SomeA   *A `json:"a,omitempty"         bson:"a,omitempty"`

      



Instead, just one place and all is well :

SomeA   *A `json:"a,omitempty" bson:"a,omitempty"`

      

+5


source







All Articles