Firestore选择where not not null

cha*_*gne 15 javascript firebase google-cloud-firestore

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

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

user = {
    firstName: 'blabla',
    lastName: 'bloblo',
    equipments: {
        123: 'blue',
        124: 'red'
    }
}
Run Code Online (Sandbox Code Playgroud)

我想让所有在设备中拥有一定设备的员工.让我们说123.

它来自Employees的Select*,其中equipment.123不为null.我试过了:

firestore.collection('employees').where(`equipments.${equipmentId}`, '!=', null)
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

我似乎无法使其发挥作用.你能帮助我吗.

Ros*_*des 32

Firestore没有"不等于"运营商.但是看一下这个逻辑,你要做的就是查询是String和否的值null.如果将String传递给函数,Firestore可以执行此操作where().

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

firestore.collection('employees').where('equipments.${equipm??entId}', '<', '\uf8ff')
Run Code Online (Sandbox Code Playgroud)

或者您可以只查询高于""(空String)的值:

firestore.collection('employees').where('equipments.${equipm??entId}', '>', '')
Run Code Online (Sandbox Code Playgroud)

  • 更简单的是> ="" (11认同)
  • 哇,我想知道我怎么没有想到这一点。谢谢@DanMcGrath (3认同)
  • 请注意,“!=”和“not-in”是:“查询运算符都不会匹配指定字段不存在的文档。”[firebase](https://firebase.google.com/support/release-notes /js#cloud-firestore_3) (2认同)

小智 21

FWIW 由于 Firestore 索引稀疏 [1],您可以执行以下操作:

firestore.collection('employees').orderBy(`equipments.${equipm??entId}`)
Run Code Online (Sandbox Code Playgroud)

并且您只会获得设置了该字段的文档。但是,如果您null在数据库中显式设置字段,您将首先获得空值,因此如果您想避免显式空值,您可以执行以下操作:

firestore.collection('employees').orderBy('equipments.${equipm??entId}').startAfter(null);
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢@rockwotj,`.startAfter(null)`正是我所需要的! (2认同)