Skip to content

Instantly share code, notes, and snippets.

@j2gg0s
Created May 26, 2021 14:19
Show Gist options
  • Select an option

  • Save j2gg0s/fe6db4a54c8b05d5fea0fe0395337374 to your computer and use it in GitHub Desktop.

Select an option

Save j2gg0s/fe6db4a54c8b05d5fea0fe0395337374 to your computer and use it in GitHub Desktop.
Surprise with MongoDB Extended JSON
package main
import (
"testing"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func TestUnmarshalExtJSON(t *testing.T) {
doc := `{"_id":{"$oid":"5ff5b89ecbc9590001210d5b"},"x":"1006007-154305-18344992668-17136650599","y":{},"z":0,"rule_group_id":{"$oid":"5ff599d4fa3f7f0012d5d3d0"},"m":""}`
t.Run("ignore field y", func(t *testing.T) {
foo := struct {
ID primitive.ObjectID `bson:"_id"`
RuleGroupID primitive.ObjectID `bson:"rule_group_id"`
}{}
err := bson.UnmarshalExtJSON([]byte(doc), false, &foo)
require.NoError(t, err)
require.Equal(t, "5ff5b89ecbc9590001210d5b", foo.ID.Hex())
require.Equal(t, "000000000000000000000000", foo.RuleGroupID.Hex())
})
t.Run("with field y", func(t *testing.T) {
foo := struct {
ID primitive.ObjectID `bson:"_id"`
RuleGroupID primitive.ObjectID `bson:"rule_group_id"`
Y interface{} `bson:"y"`
}{}
err := bson.UnmarshalExtJSON([]byte(doc), false, &foo)
require.NoError(t, err)
require.Equal(t, "5ff5b89ecbc9590001210d5b", foo.ID.Hex())
require.Equal(t, "5ff599d4fa3f7f0012d5d3d0", foo.RuleGroupID.Hex())
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment