Open Elojah opened 5 years ago
Any update on this? This creates wierd behaviour and requires us to write cutsom marshal code for many structs.
Possibly related, and a quick way to see the error:
package main
import (
"testing"
"github.com/globalsign/mgo/bson"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type TestStruct struct {
Inner []bool
}
func TestUnmarshal(t *testing.T) {
a := TestStruct{}
aBSON, err := bson.Marshal(a)
require.NoError(t, err)
b := TestStruct{}
require.NoError(t, bson.Unmarshal(aBSON, &b))
assert.Equal(t, a, b)
}
Will give the following test failure:
=== RUN TestUnmarshal
prog.go:23:
Error Trace: prog.go:23
Error: Not equal:
expected: main.TestStruct{Inner:[]bool(nil)}
actual : main.TestStruct{Inner:[]bool{}}
Diff:
--- Expected
+++ Actual
@@ -1,3 +1,4 @@
(main.TestStruct) {
- Inner: ([]bool) <nil>
+ Inner: ([]bool) {
+ }
}
Test: TestUnmarshal
--- FAIL: TestUnmarshal (0.00s)
FAIL
Oh, this isn't even an accident. This is on purpose.
bson.SetRespectNilValues(true)
will fix this behavior.
Workaround:
Wrap the bson
package in your own local bson
package and add this chunk top-level. Alternatively, add it wherever you use the bson library.
func init() {
bson.SetRespectNilValues(true)
}
Probably related to: https://github.com/globalsign/mgo/pull/147
I have a struct with:
I need to differentiate
bar == nil
orbar == []string{}
.When insert + findOne with a
nil
bar:When adding
omitempty
tag previous test will be okay but test on insert + findOne with a[]string{}
bar:I have to add a layer above to handle those cases properly, it would be more convenient (and not breaking ?) to handle this directly in the driver.
What version of MongoDB are you using (
mongod --version
)?What version of Go are you using (
go version
)?What operating system and processor architecture are you using (
go env
)?What did you do?
db.Insert
+db.Find
on an embed slice.Can you reproduce the issue on the latest
development
branch?yes