[GODRIVER-1091] Find returns no document and also no error Created: 28/May/19  Updated: 27/Oct/23  Resolved: 30/May/19

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

Type: Bug Priority: Major - P3
Reporter: prakash Assignee: Unassigned
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I have a collection `users` in which I have two documents.

 

$ db.users.find({}).pretty() db.users.find({}).pretty()
 
{ 
    "_id" : ObjectId("5ced40daa900b72809092494"), 
    "name" : "Elon", 
    "age" : 46
}
{ 
    "_id" : ObjectId("5ced40dba900b72809092495"), 
    "name" : "PCP", 
    "age" : 26 
}

 

 Use case: Find all user having some filter criteria or not filter criteria.

user.go

type user struct {    
     Name string `bson:"name"`    
     Age  int    `bson:"age"`
}
 
func (u *user) save() error {    
     collection := database.Collection(userCollection)    
     ctx, cancelFunc := context.WithTimeout(context.Background(), 20*time.Second)    
     defer cancelFunc()    
     _, err := collection.InsertOne(ctx, u)    
     return err
}
 
 
func findAll() ([]user, error) {    
    collection := database.Collection(userCollection)    
    selector := bson.M{}    
    ctx, cancelFunc := context.WithTimeout(context.Background(), 20*time.Second)    
    defer cancelFunc()    
    cur, err := collection.Find(ctx, selector)    
    if err != nil {        
             return nil, err    
     }    
    fmt.Printf("\n all users (for debugging raw bson resp): %s\n",   cur.Current.String())    
    
    users := []user{}   
    if err := cur.Decode(&users); err != nil {        
        return nil, err    
    }    
    return users, nil
}
 

main.go

 

saveUser("Elon", 46)    
saveUser("PCP", 26)    
if users, err := findAll(); err != nil {        
    panic(err)    
} else
        fmt.Printf("all users: %v", users)    
}    
fmt.Printf("exiting application\n")

cur, err := collection.Find(ctx, selector) 

*is *not working as expected as the output of ** 

fmt.Printf("\n all users (for debugging raw bson resp): %s\n", cur.Current.String())

is an empty string.



 Comments   
Comment by prakash [ 28/May/19 ]

The problem is fixed by waiting for cur.Next(context.Background())

for cur.Next(context.Background()) {        
    u := user{}        
    if err := cur.Decode(&u); 
    err != nil {            
           return nil, err        
    }        
    users = append(users, u)    
}

Please close this ticket.

Comment by prakash [ 28/May/19 ]

I am using driver version v1.0.1 and  go version go1.12.5 linux/amd64

go.mongodb.org/mongo-driver v1.0.1

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