我似乎无法检查文件是否存在。如果它不存在,则会出现错误,而不仅仅是一个空文档
"error": "rpc error: code = NotFound desc = \"projects/PROJECTID/databases/(default)/documents/claimed/123abc\" not found"
有问题的代码,值已替换为占位符。
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
}
}
}
代码文档Get()说
// 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.
那么我的解决方案是只修改错误处理吗?`if err != nil { /* 检查它是否存在 */ }
** 解决方案 **
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
}
一只甜甜圈
隔江千里
相关分类