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

use nil slice in `$in` will cause "(BadValue) $in needs an array"

    • Type: Icon: Improvement Improvement
    • Resolution: Gone away
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 1.9.1
    • Component/s: None
    • None

      go version go1.18 windows/amd64

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

      MongoDB server version: 5.0.2

      package main
      
      import (
      	"context"
      	"fmt"
      
      	"go.mongodb.org/mongo-driver/bson"
      	"go.mongodb.org/mongo-driver/mongo"
      	"go.mongodb.org/mongo-driver/mongo/options"
      )
      
      var mongoClient *mongo.Client
      
      func connect() error {
      	clientOptions := options.Client().
      		ApplyURI("******").
      		SetAuth(options.Credential{
      			Username: "******",
      			Password: "******",
      		})
      
      	client, err := mongo.Connect(context.TODO(), clientOptions)
      	if err != nil {
      		return fmt.Errorf("connect mongodb err: %w", err)
      	}
      
      	err = client.Ping(context.TODO(), nil)
      	if err != nil {
      		return fmt.Errorf("ping mongodb err: %w", err)
      	}
      
      	mongoClient = client
      
      	return nil
      }
      
      func main() {
      	if err := connect(); err != nil {
      		panic(err)
      	}
      
      	// empty slice is ok
      	test([]string{})
      
      	// nil slice will panic
      	var list []string
      	test(list)
      }
      
      func test(list []string) {
      	filter := bson.M{"any": bson.M{"$in": list}}
      	_, err := mongoClient.Database("any").Collection("any").Find(context.TODO(), filter, nil)
      	if err != nil {
      		panic(err)
      	}
      }
      

      the result is ``panic: (BadValue) $in needs an array``

      now i have to check it before find , it's a little troublesome

      func test(list []string) {
      	if list == nil {
      		list = []string{}
      	}
      
      	filter := bson.M{"any": bson.M{"$in": list}}
      	_, err := mongoClient.Database("any").Collection("any").Find(context.TODO(), filter, nil)
      	if err != nil {
      		panic(err)
      	}
      }
      

      can someone help me? thank you very much

            Assignee:
            benji.rewis@mongodb.com Benji Rewis (Inactive)
            Reporter:
            anyahui741600@outlook.com yahui An
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: