登录
首页 >  Golang >  Go问答

使用 Go 从 Firestore 获取单个文档的惯用方法是什么?

来源:stackoverflow

时间:2024-04-22 10:54:39 386浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《使用 Go 从 Firestore 获取单个文档的惯用方法是什么?》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在编写一个 go 服务,用于检索具有给定 id 的单个 firestore 文档。实施草案如下。该代码似乎可以工作。 getaccount 返回 map[string] 接口{},它可以是 nil 或设置为文档数据的表示形式。

go doc firestore.documentref.get 显示:

func (d *documentref) get(ctx context.context) (_ *documentsnapshot, err 错误) get 检索文档。如果文档不存在,get 返回一个 notfound 错误,可以通过以下方式检查 status.code(err) ==codes.notfound 在这种情况下,get 返回一个非零 documentsnapshot,其 exists 方法 返回 false,其 readtime 为读操作失败的时间。

如果 status.code(err) ==codes.notfound 已经指示其存在,为什么 documentsnapshot 还包含 exists() 方法?

go doc firestore.documentsnapshot.datato 还说:

如果文档不存在,datato 将返回 notfound 错误。

我是否还应该检查代码路径中 b 点的 status.code(err) ==codes.notfound

type srv struct {
    fs *firestore.client
}

// ...

m, err := srv.getaccount(ctx, "81199475")
if err != nil {
    log.fatal(err)
}
if m == nil {
    fmt.println("not found")
    os.exit(0)
}
fmt.printf("%#v\n", m)

func (s *srv) getaccount(ctx context.context, id string) (map[string]interface{}, error) {
    docsnap, err := s.fs.doc("accounts/" + id).get(ctx)
    if status.code(err) == codes.notfound {
        return nil, nil
    }
    if err != nil {
        return nil, err
    }

    var m map[string]interface{}
    if err := docsnap.datato(&m); err != nil {
        // point b
        return nil, err
    }
    return m, nil
}

更新:有人指出,与其返回 nil 来指示未找到文档,不如将底层 firestore 错误传播到调用堆栈,或者提供自定义错误。

var ErrAccountNotFound = errors.New("account/account-not-found")

// ...

if status.Code(err) == codes.NotFound {
    return nil, ErrAccountNotFound
}

解决方案


您只需检查 get 返回的错误是否未找到。

documentsnapshot.exists() 方法对于返回多个快照的 getall 等方法很有用。当找不到单个文档时,这些方法不会返回错误。

使用 documentsnapshot.data() 简化代码:

func (s *srv) GetAccount(ctx context.Context, id string) (map[string]interface{}, error) {
    docSnap, err := s.fs.Doc("accounts/" + id).Get(ctx)
    if err != nil {
        // Translate firestorm not found to application specific not found.
        if status.Code(err) == codes.NotFound {
            err = ErrAccountNotFound
        }
        return nil, err
    }
    return docSnap.Data(), nil
}

今天关于《使用 Go 从 Firestore 获取单个文档的惯用方法是什么?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>