如何将具有nil字段的结构体插入到MongoDB中?

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

How to insert a struct with nil field to mongo?

问题

我正在尝试将一个结构体插入到MongoDB中。首先,我从一个API获取JSON数据,并将数据赋值给一个结构体。有些字段可能为nil。然后,我将结构体插入到MongoDB中。问题是,插入后,所有字段都被初始化了。例如,我有一个如下的结构体:

type VirtualMachine struct {
    VirtualMachineID    utils.SUUID               `bson:"VirtualMachineID"`
    Cdroms              []*VM.VirtualMachineCdrom `bson:"Cdroms"`
    CpuAllocatedMHz     int                       `bson:"CpuAllocatedMHz"`
    Name                string                    `bson:"Name"`
}

如果我得到的JSON数据如下:

{
    "VirtualMachineID": '16as4df663a',
    "Cdroms": null,
    "CpuAllocatedMHz": 1666,
    "Name": 'VMName'
}

在将其放入MongoDB后,null字段变成了一个空数组。我需要避免这种情况。omitempty并没有帮助,因为如果提供的字段恰好是一个空数组而不是null,它也会跳过该字段。

起初我以为是因为指针的原因,但后来我发现对所有数据类型都是如此。简而言之,如果为nil,mgo会将其转换为零值。

我觉得我在这里漏掉了什么,因为如果mgo将所有nil值都按设计转换为零值,那就太奇怪了。

英文:

I am trying to insert a struct to mongo. Firstly I get the data from an API as JSON and assign the data to a struct. Some fields might be nil. After that I insert the struct to mongoDB. So the problem I get is that when inserted, all the fields are initialized. For example I have a struct like this:

type VirtualMachine struct {
VirtualMachineID          utils.SUUID               `bson:"VirtualMachineID"`
Cdroms                    []*VM.VirtualMachineCdrom `bson:"Cdroms"`
CpuAllocatedMHz           int                       `bson:"CpuAllocatedMHz"`
Name                      string                    `bson:"Name"`
}

If I get Json data like this

{
"VirtualMachineID":'16as4df663a',
"Cdroms":null,
"CpuAllocatedMHz":1666,
"Name":'VMName'
}

after I put it to mongo, the null field becomes an empty array. I need to avoid that. 'omitempty' did not help because it skips the field as well if the provided field happens to be an empty array and not null.

Firstly I thought it was because of the pointers, but later I found that the same happens to all data types. Shortly, if its nil, mgo converts it to its zero value.

I think I am missing something here, because it would be weird if mgo converts all nil values to their zero values by design.

答案1

得分: 1

尝试使用*[]*VM.VirtualMachineCdrom(如果你不需要元素实际上是指针,可以只使用*[]VM.VirtualMachineCdrom)。nil切片等于长度为零的切片,但nil切片指针不等于零。

英文:

Try *[]*VM.VirtualMachineCdrom (or just *[]VM.VirtualMachineCdrom if you don't actually need the elements to be pointers). A nil slice == a zero length slice, but a nil pointer to a slice does not.

huangapple
  • 本文由 发表于 2017年8月11日 22:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/45637267.html
匿名

发表评论

匿名网友

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

确定