[GODRIVER-2553] docs: cursor.All code in the find API usage example leads users to a Go gotcha in the case of no results (might be bug) Created: 23/Sep/22  Updated: 13/Oct/22  Resolved: 13/Oct/22

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

Type: Improvement Priority: Unknown
Reporter: Daria Pardue Assignee: Qingyang Hu
Resolution: Won't Fix Votes: 0
Labels: buildfest-2022
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
related to GODRIVER-2589 cursor.All code in the find API usage... Backlog
Documentation Changes: Completed

 Description   

The "fully runnable example" from the Find Multiple Documents usage example page declares the results slice that is passed to `cursor.All` as

var results []bson.M

Despite the Go driver API documentation for `cursor.All` saying that the referenced slice will be "completely overwritten", in the case of no results, `results` will remain in an uninitialized state, which will be encoded as `null` in json (and bson). In contrast, if the results slice is declared as

var results []bson.M = make([]bson.M, 0, 0)
// or, equivalently
results := make([]bson.M, 0, 0)

in the case of no results, `results` will be fully initialized, and will be encoded as `[]` (the empty array) in json.

I am not sure whether this difference in behavior for the empty result set is intentional or avoidable. If it is intentional, then I think we may want to update our documentation to point out this gotcha more clearly (both in driver API docs and the examples page) and/or update our example to use the fully initialized results declaration, so that users who are relying on a consistent data structure, e.g., for returning the response in json format via a REST API, aren't led into this pitfall.



 Comments   
Comment by Qingyang Hu [ 13/Oct/22 ]

Breaking change. Will fix in the v2.0 driver.

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