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

Time:04-26

My Firestore document has a field with a value already set.

Now I want to remove the value by setting it to something that signifies "empty" such as null or undefined.

So far I have tried doing this with the updateDoc method like so:

updateDoc(documentReference,{ photoURL: undefined })

But it throws this error:

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

And setting it to null is also not allowed because if I try to set it to null like so:

updateDoc(documentReference,{ photoURL: null })

TypeScript will throw this error:

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

I found that using an empty string like updateDoc(documentReference,{ photoURL: "" }) works but it's not as elegant as null or undefined.

I will use the empty string if no other solutions are found, but perhaps there is another way?

CodePudding user response:

Firestore does not recognize javascript undefined as a valid value. You can see the valid types in the 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. Be sure to provide complete steps to reproduce.

If you want to simply remove the field altogether so that it has no type at all, just remove the field and check for the the missing field in the code the performs the query.

  • Related