[GODRIVER-1457] Cannot marshal nil value for bsoncore.Document Created: 03/Jan/20  Updated: 07/Jan/20  Resolved: 07/Jan/20

Status: Closed
Project: Go Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: David Golub Assignee: Divjot Arora (Inactive)
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

If I define an object containing a value of type bsoncore.Document such as

type Example struct {
    DocField bsoncore.Document `bson:"docField"`
}

and attempt to marshal it when DocField is nil, it will fail with the following error message:

cannot transform type currentop.Query to a BSON Document: couldn't read length from src, not enough bytes

I can get around the issue by changing the data type to a pointer *bsoncore.Document, but this is very inelegant considering that bsoncore.Document is already nullable. It would be great if this could work as originally written. If not, could we at the very least provide an error message that's indicative of why it's not working?



 Comments   
Comment by Divjot Arora (Inactive) [ 07/Jan/20 ]

Verified with david.golub offline that the omitempty approach works for their use case. Closing this ticket.

Comment by Divjot Arora (Inactive) [ 07/Jan/20 ]

Hi david.golub,

As discussed offline, the reasoning for this being an error is that a bsoncore.Document is raw BSON bytes. Because the smallest valid document is 5 bytes, an empty bsoncore.Document is not considered valid. I have verified that you can use the omitempty struct tag to skip over the empty bsoncore.Document field when marshalling. In this case, the DocField field will not be included in the resulting document. This also avoids the need to use *bsoncore.Document fields. Can you let me know if this solution works for you?

Generated at Thu Feb 08 08:36:26 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.