Skip to content
Advertisement

How to delete a field inside Firestore document – The field’s key contains dots

I am trying to delete a field inside a Firestore document using the KeyPath method.

In other words, I am converting the request body into keyPath string.

Example, converting the below request body:

{
    "preferences": {
        "settings":{
            "v1.4.3": [
                "apple"
            ]
        }
    }
}

Into keyPath: "preferences.settings.v1.4.3"

and then using this keyPath to delete the path using the following method

await userRef.update({
          "preferences.settings.v1.4.3": admin.firestore.FieldValue.delete(),
          lastUpdated: timestamp,
      });

This would work normally if the keyPath string doesn’t contains dots. However if it contains it’s assuming the v1 is an object that contains a field with key 4.

I tried to delete the field using the set function as well(see example below) but it didn’t seem to work

await userRef.set(
          {
              {
               "preferences": {
               "settings":{
               "v1.4.3": null
              }
            }
          },
              lastUpdated: timestamp,
          },
          { merge: true }
       );

Please how to solve this issue.

Advertisement

Answer

The update operation interprets dots (.) as indications that there are subfields.

Your options to write to a field that has literal dots in its name are to:

  • Use set/setDoc, which does not interpret dots as separators. If you want to update a subset of the document, pass { merge: true} as shown in the second code sample here.
  • Use a FieldPath object for the field name, rather than just the string value.
Advertisement