2

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.

6
  • 1
    Try *[]*VM.VirtualMachineCdrom. A nil slice == a zero length slice, but a nil pointer to a slice does not. Commented Aug 11, 2017 at 14:49
  • 1
    May I ask why the value must be nil? Commented Aug 12, 2017 at 9:05
  • My script runs on crontab and it compares values on Mongo and values from API if they have changed and need to be updated in mongo. But the comparison cannot happen corectly if some fields from null become zero value. I use DeepEqual to compare and it considers nil ant [] different things (of course it is supposed to). Thats Why I need to have exact data type Commented Aug 12, 2017 at 16:48
  • @Adrian Your solution is exactly what I was looking for, it solves my problem. Commented Aug 16, 2017 at 14:11
  • Glad it helped, reposted as an answer. Commented Aug 16, 2017 at 14:14

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.