golang/mgo:在插入时忽略空字段。

huangapple go评论83阅读模式
英文:

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"`

huangapple
  • 本文由 发表于 2014年9月19日 07:06:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/25923861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定