I can't seem to check if a document exists. If it doesn't exist it goes to an error rather than just an empty document
"error": "rpc error: code = NotFound desc = \"projects/PROJECTID/databases/(default)/documents/claimed/123abc\" not found"
The code in question, values have be replaced with placeholders.
package main
import (
"context"
"errors"
"cloud.google.com/go/firestore"
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "PROJECTID")
if err != nil {
log.Fatalln(err)
}
docRef := client.Collection("claimed").Doc("123abc")
doc, err := docRef.Get(ctx)
if err != nil {
return err // <----- Reverts to here
}
// Doesn't make it to here
if doc.Exists() {
return errors.New("document ID already exists")
} else {
_, err := docRef.Set(ctx, /* custom object here */)
if err != nil {
return err
}
}
}
The code documentation for Get()
says
// Get retrieves the document. If the document does not exist, Get return a NotFound error, which
// can be checked with
// status.Code(err) == codes.NotFound
// In that case, Get returns a non-nil DocumentSnapshot whose Exists method return false and whose
// ReadTime is the time of the failed read operation.
So is my solution to just modify the error handling instead? `if err != nil { /* check it exists */ }
** Solution **
docRef := client.Collection("claimed").Doc("123abc")
doc, err := docRef.Get(ctx)
if err != nil {
if status.Code(err) == codes.NotFound {
// Handle document not existing here
_, err := docRef.Set(ctx, /* custom object here */)
if err != nil {
return err
}
} else {
return err
}
}
// Double handling (???)
if doc.Exists() {
// Handle document existing here
}
CodePudding user response:
You will get an error if the document doesn't exist.
You use the fact that you get the error for non-existence.
See the documentation for Get for handling the error.
doc, err := docRef.Get(ctx)
if err != nil {
if status.Code(err) == codes.NotFound { ... }
}
}
CodePudding user response:
You must replace "PROJECTID"
in firestore.NewClient
with the value of a Google Cloud Platform Project ID.
You can find the Project ID either in the Cloud Console or through the gcloud
CLI using e.g. gcloud projects list
.