【问题标题】:How to use Firestore DocumentID __name__ in query如何在查询中使用 Firestore DocumentID __name__
【发布时间】:2020-11-22 15:21:05
【问题描述】:

我计划使用“in”查询选择器根据 ID 列表返回多个文档。但是,我已简化为在此示例中使用“==”:

collection := server.Firestore.Collection("foo")

// Add a document:

ref, _, err := collection.Add(ctx, map[string]string{"a": "b"})
if err != nil {
    panic(err)
}

// Here's the document ID:

fmt.Println("ref.ID", ref.ID)

// Get all the documents in the collection just to check it's there:

allDocs, err := collection.Query.Documents(ctx).GetAll()
if err != nil {
    panic(err)
}
fmt.Println("len(allDocs):", len(allDocs))

// Check our document is the one in the collection:

fmt.Println("allDocs[0].Ref.ID", allDocs[0].Ref.ID)

// Get the document using __name__ query:

docQuery, err := collection.Query.Where(firestore.DocumentID, "==", ref.ID).Documents(ctx).GetAll()
if err != nil {
    panic(err)
}
fmt.Println("len(docQuery):", len(docQuery))

输出:

ref.ID NF3CCjDikC9iHPubGA8o
len(allDocs): 1
allDocs[0].Ref.ID NF3CCjDikC9iHPubGA8o
len(docQuery): 0

据我所知,上面的代码应该在查询中返回一个文档。我是否错误地使用了 DocumentID ("__ name __") 选择器?

【问题讨论】:

  • 你是如何定义你在firestore.DocumentID中使用的firestore的?
  • DocumentID 是 firestore 包中的 const 字符串,其值为 __name__
  • 尝试删除查询的.GetAll()。让我知道它是否有效。
  • 这不起作用...迭代器返回iterator.Done
  • 好的,了解更多信息。我在这个测试中使用了 Firestore 模拟器。我刚刚尝试部署到生产环境,并且从最后一个查询中收到以下错误:rpc error: code = InvalidArgument desc = __key__ filter value must be a Key

标签: go google-cloud-firestore gcloud


【解决方案1】:

好的,我已经解决了。将最终查询更改为:

Where(firestore.DocumentID, "==", ref)

... 例如传递整个 *firestore.DocumentRef 而不是 string 在模拟器和生产 Firestore 中都有效。

在两种环境中传递字符串都不会返回任何结果,但是在使用模拟器时它会静默失败并且不会返回错误。

【讨论】:

    猜你喜欢
    • 2019-10-02
    • 2021-03-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多