Firestore,我们应该避免使用值类型 null 吗?

Firestore, should we avoid using value type null?

根据Firestore supported data type

  1. undefined 不是受支持的数据类型
  2. null 是受支持的数据类型

然而,根据this doc

所以既然我们不能做 x != null(我认为这会导致运行时错误)并且 not-in [...something, null] 什么都不匹配,那么在 Firestore 中使用 null 有什么意义吗?或者我们应该避免它并使用默认值。

so since we cannot do x != null

I think this results in a runtime error.

不,不是。

Is there any point using null in Firestore?

是的,您可以查询 Firestore 以获取包含具有 null 值的特定字段的文档。显然,反之亦然。

编辑:

not-in queries exclude documents where the given field does not exist.

这是有道理的,因为 Firestore 查询只能return 基于字段的存在而不是不存在的结果。

A field exists when it's set to any value, including an empty string (""), null, and NaN (not a number).

即使我们添加一个空字符串,null,或NaN,也不意味着该字段不存在。它绝对存在并拥有这些值之一。

Note that x != null evaluates to undefined. A not-in query with null as one of the comparison values does not match any documents.

这很正常,因为列表中的值为空。您不能比较 non-null 值的 null。

Note that x != null evaluates to undefined. A not-in query with null as one of the comparison values does not match any documents.

来源https://firebase.google.com/docs/firestore/query-data/queries#not-in

有 2 个陈述:

  1. x != null 计算未定义

  2. 一个 not-in 查询以 null 作为比较值之一不匹配任何文档

我通过运行一些测试

一一检查语句
  1. x != null evaluates undefined

这个说法是假的,效果很好,但可能是句子不完整,应该是x != null evaluates undefined for non-exist field

  1. A not-in query with null as one of the comparison values does not match any documents

然而,这个说法是正确的

where("x", "not-in", [null])where("x", "not-in", [...something, null]) 将始终 return 空数组,即使存在满足条件的文档

然而,文档中缺少第 3 个声明

where("x", "not-in", [...something]) 将始终排除 xnull

的文档

更新我发现了第四个行为

当 null + 1 数据类型时,例如 null + string

x != something

将包括 x 为空的文档

当有不止一种数据类型时,例如 null + string + number

x != something

将不包括 x 为空的文档

更新:第 5 个行为

x in [[{someKey:'someValue'}], [{someKey:'someValue'},{someKey:'someValue2'}], [{someKey:null}], [{someKey:'someValue'},{someKey:null}]]

将包括 x 为 [{someKey:'someValue'}] 且 x 为

的文档

[{someKey:'someValue'},{someKey:'someValue2'}]

将不包括 x 为 [{someKey:null}] 且 x 为

的文档

[{someKey:'someValue'},{someKey:null}]

同时 array-containsarray-contains-any{someKey:null}

正常工作

更新:第 6 个行为

与第 5 种行为不同,有类似的例子(我知道 inarray-contains-any 之间的要求是可搜索的),null 在 array-containsarray-contains-any 下工作正常,您可以在包含 null 的数组中搜索字段。

null 行为太复杂难以记忆,我强烈建议避免使用 null