[GODRIVER-1194] Confusing error using uninitialized bson.D as a document Created: 09/Jul/19  Updated: 27/Oct/23  Resolved: 27/Feb/23

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

Type: Bug Priority: Major - P3
Reporter: David Golden Assignee: Unassigned
Resolution: Gone away Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: File decode.go    
Issue Links:
Related
related to GODRIVER-854 Err: cannot transform type bson.D to ... Closed
related to GODRIVER-917 Difference in BSON/JSON serialization... Closed
Documentation Changes Summary:

1. What would you like to communicate to the user about this feature?
2. Would you like the user to see examples of the syntax and/or executable code and its output?
3. Which versions of the driver/connector does this apply to?


 Description   

If an uninitialized bson.D is passed to Find, the following error results:

cannot transform type primitive.D to a BSON Document: WriteNull can only write while positioned on a Element or Value but is positioned on a TopLevel

This is a very confusing error for users. As mentioned in GODRIVER-917, we differ from mgo in how we serialize a nil document, but regardless of how we resolve that ticket, I think it would be a better user experience to detect this case earlier in the call chain so we can return a meaningful error message that would help users quickly fix the problem.

I suspect that any API method (or option) that takes a document could have the same problem as Find.

Here is a repro (against master):

package main
 
import (
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)
 
func main() {
	opts := options.Client().ApplyURI("mongodb://localhost:27017")
	client, err := mongo.Connect(nil, opts)
	if err != nil {
		panic(err)
	}
 
	collection := client.Database("test").Collection("test")
 
	var filter bson.D
	cursor, err := collection.Find(nil, filter)
	if err != nil {
		panic(err)
	}
	_ = cursor
}



 Comments   
Comment by David Golden [ 09/Jul/19 ]

Additional notes:

  • An uninitialized bson.M does not error.
  • An uninitialized bson.A produces a similar error:
    • "cannot transform type primitive.A to a BSON Document: WriteNull can only write while positioned on a Element or Value but is positioned on a TopLevel"
    • Despite the confusing "WriteNull..." part, the initial part at least makes more sense in context, an "A" is not a document type.
Generated at Thu Feb 08 08:35:53 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.