golang/mgo:从insert中删除空字段

golang/mgo:从insert中删除空字段,go,bson,mgo,Go,Bson,Mgo,出于某种原因,mgo将空结构作为空值插入数据库,即使我已经设置了ommitempty选项 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,omit

出于某种原因,
mgo
将空结构作为空值插入数据库,即使我已经设置了ommitempty选项

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))
    }
}
json编码器省略了
SomeA
属性,但在数据库中它作为
“a”:null
存在。
是我做错了什么,还是根本不可能这样做?

是的,所以问题是json和bson编码器选项之间有选项卡,这就是为什么省略空不起作用。所以这是错误的:

SomeA   *A `json:"a,omitempty"         bson:"a,omitempty"`
SomeA   *A `json:"a,omitempty" bson:"a,omitempty"`
取而代之的是,只要有一个空间,一切都很好:

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

你能告诉我们你是如何将它插入mongo的吗?应该跳过这个值:我在结构A中有一个额外的字段:Id bson.ObjectId
bson:“\u Id”
,我只需调用Insert函数:err=db.mongo.C(“collection”).Insert(&b)噢,上帝。它正在工作。问题是我在json和bson编码器选项之间有选项卡,而不仅仅是一个空格。谢谢你的帮助@安德鲁-你能把它作为一个答案,并接受它来帮助其他有同样问题的人吗。