From https://godoc.org/cloud.google.com/go/firestore#example-DocumentRef-Get, example for Get:
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
docsnap, err := client.Doc("States/Ohio").Get(ctx)
if err != nil {
// TODO: Handle error.
}
In JavaScript SDK, result of Get() has exists field.
As far as I can tell in Go SDK I can't distinguish "document doesn't exist" error from e.g. network connection error.
I hacked a heuristic function:
func dbIsNotFoundError(err error) bool {
s := err.Error()
return strings.Contains(s, "code = NotFound")
}
but I would prefer a supported and documented way of doing that.
Try
import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
if grpc.Code(err) == codes.NotFound
Thanks, I've tested it and it worked.
That being said, I imagine it's a common thing to do and impossible to figure out hence 2 suggestions:
firestore.IsNotFoundError(err). It's not to save few import lines but to improve discoverability of this functionalityHowever, if we determene existence of a document based on an error, why do we even have a method Exists() on type DocumentSnapshot?
seems kind of redundant to use the Exists() method.
Since you have to call Get() handle a possible error, then call the Exists() method. If the error from the Get() is a not found you would need to explicitly ignore it then call Exists()
am i missing something?
I can imagine situations where it's more convenient to call an Exists() method. But, that's a good question. :)
If Get() returns an error with grpc.Code(err) == codes.NotFound, you don't have to call Exists(). At that point, you already know the document you were trying to get does not exist.
grpc.Code(err) is deprecated.
but, we can use status.Code(err).
https://pkg.go.dev/google.golang.org/grpc/status#Code
import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// deprecated
// if grpc.Code(err) == codes.NotFound
if status.Code(err) == codes.NotFound
Most helpful comment
However, if we determene existence of a document based on an error, why do we even have a method Exists() on type DocumentSnapshot?