Go - 检查 Firestore 文档是否存在

Ari*_*Ari 0 go google-cloud-firestore

我似乎无法检查文档是否存在。如果它不存在,则会出现错误,而不仅仅是一个空文档

 "error": "rpc error: code = NotFound desc = \"projects/PROJECTID/databases/(default)/documents/claimed/123abc\" not found"
Run Code Online (Sandbox Code Playgroud)

有问题的代码,值已替换为占位符。

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码文档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.
Run Code Online (Sandbox Code Playgroud)

那么我的解决方案是只修改错误处理吗?`if err != nil { /* 检查它是否存在 */ }

** 解决方案 **

 "error": "rpc error: code = NotFound desc = \"projects/PROJECTID/databases/(default)/documents/claimed/123abc\" not found"
Run Code Online (Sandbox Code Playgroud)

Daz*_*kin 5

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

您使用了您收到不存在错误的事实。

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

doc, err := docRef.Get(ctx)
  if err != nil {
    if status.Code(err) == codes.NotFound { ... }
  }
}
Run Code Online (Sandbox Code Playgroud)