从Firestore查询中获取单个项目

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

Get a single item from the query Firestore

问题

我正在尝试使用Golang从Firestore Firebase获取单个文档。我知道如果有一个id,这很容易实现,你可以像这样编写代码:

database.Collection("profiles").Doc(userId).Get(ctx)

在我的情况下,我需要使用Where条件来查找特定的文档,这就是我卡住的地方。到目前为止,我只能想到以下的解决方案:

database.Collection("users").Where("name", "==", "Mark").Limit(1).Documents(ctx).GetAll()

显然,这不是最好的解决方案,因为我只需要找到符合条件的一个(基本上是第一个)文档,并且使用GetAll()看起来非常奇怪。什么是最佳的方法呢?

英文:

I'm trying to get a single document from the Firestore Firebase using Golang. I know that it is easy if you have an id, you can write something like this:

database.Collection("profiles").Doc(userId).Get(ctx)

In my case I need to find a specific document using a Where condition, and this is where I get stuck. So far I was able to come up only with the following:

database.Collection("users").Where("name", "==", "Mark").Limit(1).Documents(ctx).GetAll()

And it is obviously not the best solution since I am looking only for one (basically the first) document which follows the condition and using GetAll() seems really weird. What would be the best approach?

答案1

得分: 3

应用程序可以调用NextStop来获取单个文档:

func getOne(ctx context.Context, q firestore.Query) (*firestore.DocumentSnapshot, error) {
    it := q.Limit(1).Documents(ctx)
    defer it.Stop()
    snap, err := it.Next()
    if err == iterator.Done {
        err = fmt.Errorf("没有匹配的文档")
    }
    return snap, err
}
英文:

The application can call Next and Stop to get a single document:

func getOne(ctx context.Context, q firestore.Query) (*firestore.DocumentSnapshot, error) {
	it := q.Limit(1).Documents(ctx)
	defer it.Stop()
	snap, err := it.Next()
	if err == iterator.Done {
		err = fmt.Errorf("no matching documents")
	}
	return snap, err
}

huangapple
  • 本文由 发表于 2021年9月20日 23:30:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/69257116.html
匿名

发表评论

匿名网友

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

确定