Uploaded image for project: 'Go Driver'
  1. Go Driver
  2. 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)



    • Icon: Improvement Improvement
    • Resolution: Won't Fix
    • Icon: Unknown Unknown
    • None
    • None
    • Docs
    • Completed


      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.




            qingyang.hu@mongodb.com Qingyang Hu
            daria.pardue@mongodb.com Daria Pardue
            0 Vote for this issue
            3 Start watching this issue