[GODRIVER-1004] SingleResult.Decode only works once Created: 29/Apr/19  Updated: 28/Oct/23  Resolved: 02/May/19

Status: Closed
Project: Go Driver
Component/s: CRUD
Affects Version/s: 1.0.1
Fix Version/s: 1.0.2

Type: Improvement Priority: Major - P3
Reporter: David Golden Assignee: Divjot Arora (Inactive)
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Backports
backported by GODRIVER-1014 backport "SingleResult.Decode only wo... Closed
Backwards Compatibility: Fully Compatible

 Description   

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



 Comments   
Comment by Githook User [ 02/May/19 ]

Author:

{'email': 'divjot.arora@10gen.com', 'name': 'Divjot Arora', 'username': 'divjotarora'}

Message: Allow SingleResult Decode and DecodeBytes methods to be called more than once.

GODRIVER-1004

Change-Id: Ia1a7471dda022414acccba2b81e13822a24285fb
Branch: release/1.0
https://github.com/mongodb/mongo-go-driver/commit/f418f6a8511c438a0d6941d77a9404ef66e27ccf

Comment by Githook User [ 02/May/19 ]

Author:

{'email': 'divjot.arora@10gen.com', 'name': 'Divjot Arora', 'username': 'divjotarora'}

Message: Allow SingleResult Decode and DecodeBytes methods to be called more than once.

GODRIVER-1004

Change-Id: Ia1a7471dda022414acccba2b81e13822a24285fb
Branch: master
https://github.com/mongodb/mongo-go-driver/commit/229a9c94a4735eccfc431ea183e0942de7569f58

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