Go - 检查 Firestore 文档是否存在

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


 "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

    }


函数式编程
浏览 76回答 2
2回答

一只甜甜圈

如果文档不存在,您将收到错误消息。您使用的事实是您得到不存在的错误。请参阅Get的文档以处理错误。doc, err := docRef.Get(ctx)&nbsp; if err != nil {&nbsp; &nbsp; if status.Code(err) == codes.NotFound { ... }&nbsp; }}

隔江千里

您必须将"PROJECTID"in替换firestore.NewClient为 Google Cloud Platform 项目 ID 的值。您可以在Cloud Console中或通过gcloudCLI 使用例如gcloud projects list.
打开App,查看更多内容
随时随地看视频慕课网APP