【发布时间】:2014-09-18 23:06:18
【问题描述】:
出于某种原因,mgo 将空结构作为空值插入到数据库中,即使我设置了 omitempty 选项。
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 存在。
是我做错了什么,还是根本不可能这样做?
【问题讨论】:
-
你能告诉我们你是如何将它插入 mongo 的吗?
-
我在结构 A 中有一个附加字段:Id bson.ObjectId
bson:"_id"我只是调用了插入函数:err = db.Mongo.C("collection").Insert(&b) -
天哪。它现在正在工作。问题是我在 json 和 bson 编码器选项之间有标签,而不仅仅是一个空格。感谢您的帮助!
-
@Andrew - 您能否将其发布为答案并接受它以帮助遇到同样问题的其他人。