英文:
golang/mgo: leave out empty fields from insert
问题
由于某种原因,即使我已经设置了omitempty选项,mgo
仍然将空结构插入数据库中作为null值。
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
的形式存在。
我做错了什么,还是说无法以这种方式实现?
英文:
For some reason mgo
inserts the empty struct into the db as null value even though I've set 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 out the SomeA
property but in the database it's there as "a" : null
.
Am I doing something wrong, or it's simply not possible to do it this way?
答案1
得分: 8
是的,问题是在json和bson编码器选项之间有制表符,这就是为什么omitempty不起作用的原因。所以这是错误的:
SomeA *A `json:"a,omitempty" bson:"a,omitempty"`
而应该只有一个空格,就没问题了:
SomeA *A `json:"a,omitempty" bson:"a,omitempty"`
英文:
Yeah, so problem was having tabs between the json and bson encoder options, that's why omitempty didn't work. So this is wrong:
SomeA *A `json:"a,omitempty" bson:"a,omitempty"`
Instead just have a single space and it's all good:
SomeA *A `json:"a,omitempty" bson:"a,omitempty"`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论