为了账号安全,请及时绑定邮箱和手机立即绑定

Go - 检查 Firestore 文档是否存在

Go - 检查 Firestore 文档是否存在

Go
函数式编程 2022-10-10 20:03:24
我似乎无法检查文件是否存在。如果它不存在,则会出现错误,而不仅仅是一个空文档 "error": "rpc error: code = NotFound desc = \"projects/PROJECTID/databases/(default)/documents/claimed/123abc\" not found"有问题的代码,值已替换为占位符。package mainimport (    "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    }
查看完整描述

2 回答

?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

如果文档不存在,您将收到错误消息。


您使用的事实是您得到不存在的错误。


请参阅Get的文档以处理错误。


doc, err := docRef.Get(ctx)

  if err != nil {

    if status.Code(err) == codes.NotFound { ... }

  }

}


查看完整回答
反对 回复 2022-10-10
?
隔江千里

TA贡献1906条经验 获得超10个赞

您必须将"PROJECTID"in替换firestore.NewClient为 Google Cloud Platform 项目 ID 的值。

您可以在Cloud Console中或通过gcloudCLI 使用例如gcloud projects list.


查看完整回答
反对 回复 2022-10-10
  • 2 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信