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

Find returns no document and also no error

    XMLWordPrintableJSON

Details

    • Icon: Bug Bug
    • Resolution: Works as Designed
    • Icon: Major - P3 Major - P3
    • None
    • None
    • None
    • None

    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.

      Attachments

        Activity

          People

            Unassigned Unassigned
            prakashpandey prakash
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: