如何更新 Firestore 字段以为其提供空值(未定义或 null)?

How to update a Firestore field to give it an empty value (undefined or null)?

我的 Firestore 文档有一个字段已经设置了值。

现在我想删除该值,方法是将其设置为表示“空”的值,例如 nullundefined

到目前为止,我已尝试使用 updateDoc 方法进行此操作,如下所示:

updateDoc(documentReference,{ photoURL: undefined })

但是它抛出这个错误:

Function updateDoc() called with invalid data. Unsupported field value: undefined (found in field photoURL in document users/d23xxxxxxxxxxxxxxx12)

并且将其设置为 null 也是不允许的,因为如果我尝试将其设置为 null,就像这样:

updateDoc(documentReference,{ photoURL: null })

TypeScript 会抛出这个错误:

Type 'null' is not assignable to type 'FieldValue | Partial | undefined'.

我发现使用像 updateDoc(documentReference,{ photoURL: "" }) 这样的空字符串是可行的,但它不如 nullundefined.

优雅

如果找不到其他解决方案,我将使用空字符串,但也许还有其他方法?

Firestore 无法将 javascript undefined 识别为有效值。您可以在 documentation. Null is a valid type, so you should be able to use that. If you are not, then you should file a bug against the SDK that you're using. If you're using the web client SDK, use this GitHub 中看到有效类型。请务必提供完整的重现步骤。

如果您只想完全删除该字段,使其完全没有类型,只需 并检查执行查询的代码中缺少的字段。