Uploaded image for project: 'Go Driver'
  1. Go Driver
  2. GODRIVER-1004

SingleResult.Decode only works once

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 1.0.2
    • Affects Version/s: 1.0.1
    • Component/s: CRUD
    • None
    • Fully Compatible

      Calling Decode twice on a SingleResult gives ErrNoDocument on the second invocation. This may be surprising to users, as there's no reason why decoding a result shouldn't be idempotent, so this should either be fixed or clearly documented.

      Test program:

      package main
      
      import (
      	"context"
      	"fmt"
      	"log"
      
      	"go.mongodb.org/mongo-driver/bson"
      	"go.mongodb.org/mongo-driver/bson/primitive"
      	"go.mongodb.org/mongo-driver/mongo"
      )
      
      type X struct {
      	ID   primitive.ObjectID `bson:"_id,omitempty"`
      	Name string             `bson:"name"`
      }
      
      func main() {
      	ctx := context.Background()
      
      	client, err := mongo.Connect(ctx)
      	if err != nil {
      		log.Fatal(err)
      	}
      
      	coll := client.Database("test").Collection("decodeit")
      	_ = coll.Drop(ctx)
      
      	doc := X{Name: "hello world"}
      	res, err := coll.InsertOne(ctx, doc)
      	if err != nil {
      		log.Fatal(err)
      	}
      	id := res.InsertedID
      	fmt.Println("Inserted", id)
      
      	got := coll.FindOne(ctx, bson.D{{"_id", id}})
      	if got.Err() != nil {
      		log.Fatal(got.Err())
      	}
      
      	var doc2 X
      	err = got.Decode(&doc2)
      	if err != nil {
      		log.Fatalf("doc2 %v", err)
      	}
      	fmt.Println("Doc2", doc2)
      
      	var doc3 X
      	err = got.Decode(&doc3)
      	if err != nil {
      		log.Fatalf("doc3 %v", err)
      	}
      	fmt.Println("Doc3", doc3)
      }
      

      Result:

      $ go run main.go
      Inserted ObjectID("5cc6589337cb74f2796364e9")
      Doc2 {ObjectID("5cc6589337cb74f2796364e9") hello world}
      2019/04/28 21:51:15 doc3 mongo: no documents in result
      exit status 1
      

            Assignee:
            divjot.arora@mongodb.com Divjot Arora (Inactive)
            Reporter:
            david.golden@mongodb.com David Golden
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: