Detailed steps to reproduce the problem?
The bson codec will instantiate a pointer field decoded from null data if the user defines a UnmarshalBSONValue. For example:
package main import ( "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) type DBInt64 int64 type Product struct { TotalForSell *DBInt64 `json:"total_for_sell" bson:"total_for_sell,omitempty"` } func (i *DBInt64) UnmarshalBSONValue(t bsontype.Type, value []byte) error { return nil } func main() { idx, doc := bsoncore.AppendDocumentStart(nil) doc = bsoncore.AppendNullElement(doc, "total_for_sell") doc, err := bsoncore.AppendDocumentEnd(doc, idx) if err != nil { panic(err) } bytes := bson.Raw(doc) got := Product{} if err := bson.Unmarshal(bytes, &got); err != nil { panic(err) } if got.TotalForSell != nil { fmt.Println("null value decoded as non-nil") } }
Output:
❯ go run custom_type_with_pointer.go
null value decoded as non-nil
Definition of done: what must be done to consider the task complete?
If the bsonrw.ValueReader is bsontype.Null, then we should return vr.ReadNull() rather than using reflect to instantiate data to decode. That is, the following block should be added before this line:
if vr.Type() == bsontype.Null { val.Set(reflect.Zero(val.Type())) return vr.ReadNull() }
The exact Go version used, with patch level:
go version go1.23.1 darwin/arm64
The exact version of the Go driver used:
1.17.1
Describe how MongoDB is set up. Local vs Hosted, version, topology, load balanced, etc.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.1
Using MongoDB: 8.0.0-rc18
Using Mongosh: 2.3.1
The operating system and version (e.g. Windows 7, OSX 10.8, ...)
OSX 14.7.1
Security Vulnerabilities
NA
- is related to
-
GODRIVER-3470 v1.17.2 regression UnmarshalBSONValue not called - worked on v1.17.1
- In Code Review