英文:
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
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论