Firestore 查询对象键存在的文档

ntg*_*ner 4 google-cloud-firestore

我正在编写一个跟踪事件的应用程序。我正在使用 firestore 拥有一个主要集合,其中events将每个事件作为文档保存。每个文档都有自己的详细信息(包括roles对象)以及事件中自己的步骤集合。

集合对象如下所示:

events > [collection]
    eventid1 > [doc]
        steps > [collection]
        location: "Even Center",
        notes: "Some notes here",
        timestamp: 1272153600,
        title: "A great event",
        roles:
            userID1: 0, //numbers to define role type
            userID2: 1,
            userID3: 1,
Run Code Online (Sandbox Code Playgroud)

我想做的是查询roles.userID1存在的任何事件。我知道 firestore 没有子集合查询,所以这是我最接近解决这个问题的方法。

只有 3 个“角色”(0 = 所有者、1 = 编辑者、2 = 查看者)。我尝试编写三个查询并使用 组合查询.where("roles." + this.user.uid, "==", 0)。这会起作用(尽管事后我遇到了一些数组问题),但我不想为每个查看此内容的用户进行 3 次调用。

我在某处的随机评论中看到您可以使用查询.where("roles." + this.user.uid, "<", ""),但这对我不起作用。

有没有办法编写一个查询来查看对象中的键是否存在?

Joh*_*ika 9

您可以用来orderBy查找存在对象键的文档。例如,假设您有一个如下所示的文档:

{
  "users": {
    "bob": {},
    "sam": {},
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以找到包含users.bob以下内容的所有文档:

.orderBy('users.bob')
Run Code Online (Sandbox Code Playgroud)


ntg*_*ner 5

正如我上面的评论所述,我能够回答我自己的问题,因为我不小心为自己的成功做好了准备。

早些时候,我决定为我的角色赋予一个数字值,而不是字符串值。0、1 和 2。现在看到这一点,我意识到.where只需使用 就可以有效地使用该子句< 3

我的查询现在包括.where("roles." + this.user.uid, "<", 3).

这有效地查看了角色的子对象(整个字符串类似于.where("roles.ehHH-scSd-d222-njsl-LLewS, "<", 3). (3 不是角色,因此如果您有超过 3 个角色,请增加数字)。