Go – 检查 Firestore 文档是否存在

huangapple go评论81阅读模式
英文:

Go - check Firestore document exists

问题

我无法检查文档是否存在。如果文档不存在,它会返回一个错误而不是一个空文档。

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

以下是相关的代码,其中的值已被替换为占位符。

package main

import (
	"context"
	"errors"
	"log"

	"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 // <----- 返回到这里
	}

	// 不会执行到这里
	if doc.Exists() {
		return errors.New("document ID already exists")
	} else {
		_, err := docRef.Set(ctx, /* 自定义对象 */)
		if err != nil {
			return err
		}
	}
}

Get() 方法的代码文档中写道:

// Get 检索文档。如果文档不存在,Get 返回一个 NotFound 错误,可以通过以下方式检查:
//    status.Code(err) == codes.NotFound
// 在这种情况下,Get 返回一个非空的 DocumentSnapshot,其 Exists 方法返回 false,ReadTime 是失败读取操作的时间。

所以,我的解决方案是修改错误处理部分吗?if err != nil { /* 检查文档是否存在 */ }

解决方案

docRef := client.Collection("claimed").Doc("123abc")
doc, err := docRef.Get(ctx)
if err != nil {
    if status.Code(err) == codes.NotFound {
        // 在此处理文档不存在的情况
        _, err := docRef.Set(ctx, /* 自定义对象 */)
        if err != nil {
            return err
        }
    } else {
        return err
    }
}

// 双重处理(???)
if doc.Exists() {
    // 在此处理文档存在的情况
}
英文:

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

 &quot;error&quot;: &quot;rpc error: code = NotFound desc = \&quot;projects/PROJECTID/databases/(default)/documents/claimed/123abc\&quot; not found&quot;

The code in question, values have be replaced with placeholders.

package main

import (
	&quot;context&quot;
    &quot;errors&quot;
	&quot;cloud.google.com/go/firestore&quot;

func main() {

    ctx := context.Background()
    client, err := firestore.NewClient(ctx, &quot;PROJECTID&quot;)
	if err != nil {
		log.Fatalln(err)
	}

    docRef := client.Collection(&quot;claimed&quot;).Doc(&quot;123abc&quot;)
    doc, err := docRef.Get(ctx)
	if err != nil {
		return err // &lt;----- Reverts to here
	}

    // Doesn&#39;t make it to here
	if doc.Exists() {
		return errors.New(&quot;document ID already exists&quot;)
	} 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(&quot;claimed&quot;).Doc(&quot;123abc&quot;)
    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
    }


答案1

得分: 4

如果文档不存在,你将会收到一个错误。

你可以利用这个错误来处理不存在的情况。

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

doc, err := docRef.Get(ctx)
  if err != nil {
    if status.Code(err) == codes.NotFound { ... }
  }
}
英文:

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 { ... }
  }
}

huangapple
  • 本文由 发表于 2021年11月12日 07:32:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/69936219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定