Firestore客户端无法连接指定数据库问题求助
解决方案
问题根源是你没有显式指定要连接的Firestore数据库ID,Go语言的Firestore SDK默认会尝试连接名为default的数据库,而你实际创建的是名为test的数据库,因此需要在初始化客户端时添加指定数据库的配置。
修改后的代码
package main import ( "context" "log" "cloud.google.com/go/firestore" "google.golang.org/api/option" ) var ( firestoreClient *firestore.Client ) func initializeFirestore() { ctx := context.Background() // 补充定义ctx变量 var err error credentialsFilePath := "config/serviceaccount.json" opt := option.WithCredentialsFile(credentialsFilePath) // 通过firestore.WithDatabase指定要连接的数据库名称 firestoreClient, err = firestore.NewClient(ctx, "你的GCP项目ID", opt, firestore.WithDatabase("test")) if err != nil { log.Fatalf("Failed to create Firestore client: %v", err) } _, err = firestoreClient.Collections(ctx).Next() if err != nil { log.Fatalf("Failed to verify Firestore connection: %v", err) } }
关键修改点
- 添加
firestore.WithDatabase("test")选项,明确指定要连接的数据库名称 - 补充了
ctx变量的定义(原代码中未定义该变量,会导致编译错误) - 注意
firestore.NewClient的第二个参数是你的GCP项目ID,而非数据库名称
内容的提问来源于stack exchange,提问作者Youshikyou
相关产品推荐
相关产品推荐

