【问题标题】:Is there an `exists` where clause I can use with firestore?是否有我可以与 firestore 一起使用的“exists” where 子句?
【发布时间】:2018-05-17 17:37:52
【问题描述】:

用例:查找我参与的对话。

给定一组对话,有没有办法在嵌套对象的属性上使用 where exists 子句?我正在使用一个带有 id 的对象,因为它是关键,希望它是我可以运行 where 查询的东西。我应该把参与者字段放在一个数组中吗?

 db.collection('conversations')
            .where('participants.${userId}', 'exists', true)
            .get()
            .then(() => {
                // ...
            });

示例对话对象

{ 
  id: 'foo'
  participants: { 
    userIdA: {
       username: 'bar'
    },
    userIdB: {
       username: 'joe'
    }
  }
}

【问题讨论】:

  • 我记得从第一个值开始的一些事情。所以.where('participants.${userId}', '>=', ' ')(空格是第一个可打印的 ASCII 字符)。 .orderBy('participants.${userId}') 也可能有效。
  • 所以 orderBy 有效,但 >= '' 无效。 orderBy 技巧让我有点紧张,以防它的行为发生变化。是否在文档中的某个地方设置了 order by 子句中带有 null 的记录不会在集合中返回?或者,有没有办法我应该调整我的数据模式以使这个查询更容易?也许将参与者从嵌套对象中拉出来并使其成为顶级属性..在这种情况下,我会将对话硬编码为必须设置在属性 userAuserB 的参与者
  • 这个阶段的顺序已经很好地定义了,尽管我很惊讶>= 不起作用。对此感到抱歉。

标签: javascript google-cloud-firestore


【解决方案1】:

假设您的示例对话对象是一个完整示例,您只需将每个参与的 userId 设置为等于 true,然后进行如下查询:

db.collection('conversations')
  .where(`participants.${userId}`, ==, true)
  .get()
  .then(snapshot => {
    // ...
  });

如果您需要了解有关特定用户的更多信息,例如他们的姓名,您可以在 users 集合中查找,因为您知道他们的 ID 是什么。

db.doc(`users/${userId}`)
  .get()
  .then(snapshot => {
    // ...
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 2010-10-10
    • 2016-05-06
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多