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
- backported by
-
GODRIVER-1014 backport "SingleResult.Decode only works once"
- Closed