【问题标题】:golang/mgo: leave out empty fields from insertgolang/mgo:从插入中省略空字段
【发布时间】: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 - 您能否将其发布为答案并接受它以帮助遇到同样问题的其他人。

标签: go bson mgo


【解决方案1】:

是的,所以问题在于 json 和 bson 编码器选项之间有制表符,这就是 omitempty 不起作用的原因。所以这是错误

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

而只是有一个空格,这一切都

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 2023-03-05
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多