firebasegogoogle-cloud-platformgoogle-cloud-firestore

firebase client cannot connect to correct firebase database


I am trying to initiatlize the firebase client and connect to the firebase database.

package main

import (
    "log"

    "cloud.google.com/go/firestore"
    "google.golang.org/api/option"
)

var (
    firestoreClient *firestore.Client
)

func initializeFirestore() {
    var err error
    credentialsFilePath := "config/serviceaccount.json"
    opt := option.WithCredentialsFile(credentialsFilePath)

    firestoreClient, err = firestore.NewClient(ctx, "test", opt)
    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)
    }
}

I keeps getting the error that

Failed to verify Firestore connection: rpc error: code = NotFound desc = The database (default) does not exist for project test Please visit https://console.cloud.google.com/datastore/setup?project=cyberprayer to add a Cloud Datastore or Cloud Firestore database.
exit status 1

I have created the database called test and it is native mode. I don't know why it keeps connecting to the (default) which I don't have it.


Solution

  • The documentation on creating a client shows this code snippet:

    ctx := context.Background()
    client, err := firestore.NewClient(ctx, "projectID")
    

    So the second argument to NewClient is the project ID. Since you're passing test there, it looks for a project with ID test, which doesn't exist.


    To pass in the database ID too, you'll want to call the NewClientWithDatabase method, which has this signature:

    func NewClientWithDatabase(ctx context.Context, projectID string, databaseID string, opts ...option.ClientOption) (*Client, error)
    

    So if I read that correctly, it should be something like:

    firestoreClient, err = firestore.NewClientWithDatabase(ctx, "your-actual-project-id", "test", opt)