【问题标题】:Firestore select where is not nullFirestore 选择不为空的位置
【发布时间】:2018-07-06 20:47:01
【问题描述】:

我正在使用 firebase 来管理我的项目,但我无法使用 where 子句创建查询,其中某些值不为空。

示例:我有一组员工。每个都有一个设备列表作为对象,其中键是设备 ID,值是颜色。

user = {
    firstName: 'blabla',
    lastName: 'bloblo',
    equipments: {
        123: 'blue',
        124: 'red'
    }
}

我想得到所有在设备中拥有某种设备的员工。假设是 123。

涉及Select * from Employees,其中设备.123 不为空。我试过了:

firestore.collection('employees').where(`equipments.${equipmentId}`, '!=', null)

但它不起作用。

我似乎无法让它工作。你能帮帮我吗?

【问题讨论】:

  • Cloud Firestore 没有“不等于”运算符。见stackoverflow.com/questions/47251919/…
  • 正如@FrankvanPuffelen 提到的,没有“不等于”运算符,但我突然想到了一种解决方法。您可以尝试使用firestore.collection('employees').where('equipments.${equipmentId}', '<', '\uf8ff')。我从未对此进行过测试,但我相信值得一试。
  • 糟糕...我误读为“不存在的地方”。 “存在的地方”确实通常是可行的。听起来像是@RosárioPereiraFernandes 的答案! :-)
  • 我只是检查不存在的文档中的任何字段(名为 .exists 的字段)是否等于 true

标签: javascript firebase google-cloud-firestore


【解决方案1】:

2020 年 9 月更新:v7.21.0 引入了对不等于 (!=) 查询的支持! 这意味着您现在可以使用下面的代码:

firestore.collection('employees').where(`equipments.${equipm‌​entId}`, '!=', null)

上一个答案:

Firestore 没有“不等于”运算符。但是看看逻辑,你想要做的是查询String 的值,而不是nullFirestore can do that 如果您将字符串传递给 where() 函数。

所以你可以做的是查询低于\uf8ff的值。这是 Unicode 范围内的一个非常高的代码点。由于它位于 Unicode 中的大多数常规字符之后,因此此查询将返回 String 类型的所有内容:

firestore.collection('employees').where(`equipments.${equipm‌​entId}`, '<', '\uf8ff')

或者您可以简单地查询高于“”的值(空String):

firestore.collection('employees').where(`equipments.${equipm‌​entId}`, '>', '')

【讨论】:

  • 更简单的是 >= ""
  • 哇,我想知道我怎么没想到。谢谢@DanMcGrath
  • 不幸的是,此答​​案似乎不适用于具有文档引用的字段。
  • 请注意!=not-in是:Neither query operator will match documents where the specified field is not present.firebase
【解决方案2】:

FWIW 因为 Firestore 索引是稀疏的 [1],您可以执行以下操作:

firestore.collection('employees').orderBy(`equipments.${equipm‌​entId}`)

而且您只会获得设置了该字段的文档。但是,如果您在数据库中将字段显式设置为 null,您将首先获得空值,因此如果您想避免显式空值,您可以这样做:

firestore.collection('employees').orderBy('equipments.${equipm‌​entId}').startAfter(null);

[1]:稀疏表示如果文档中不存在该字段,Cloud Firestore 不会在该文档/字段的索引中创建索引条目。

【讨论】:

  • 谢谢@rockwotj,.startAfter(null) 正是我所需要的!
猜你喜欢
  • 2012-05-07
  • 2014-04-13
  • 2011-05-27
  • 2019-04-05
  • 2019-02-25
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
相关资源
最近更新 更多