Firebase Version 9 Tutorial (Modular)

Firebase Version 8 Tutorial (Namespaced)

Firebase V9 Firestore DELETE Document Field Using updateDoc()

Last modified on June 30th, 2022
Firebase Javascript

Using the updateDoc() method, you can delete one or more document field(s) in the Firebase Firestore Database.

Let’s say you want to delete the field called code from a sample Firestore document like below.

Import Firestore and de-structure the four methods that we need to perform the delete operation to one or more document field(s).

  • getDatabase()
  • doc()
  • updateDoc()
  • deleteField()
import { getFirestore, doc, updateDoc, deleteField } from "firebase/firestore";

Then, initialize the Firestore database.

const db = getFirestore(app);

The updateDoc() method takes two arguments:

  • doc()
  • data {}

Doc()

The first argument of the updateDoc() method is doc().

The doc() method takes three arguments.

  • database → db
  • collection name → cities
  • Document ID → yftq9RGp4jWNSyBZ1D6L (see the sample document screenshot above)

Call the doc() method with these arguments and assign it to a constant called docRef.

const docRef = doc(db, "cities", "yftq9RGp4jWNSyBZ1D6L");

Delete Field()

The second argument of the updateDoc() method is the JavaScript object with the field name(s) that you want to delete.

In this case: code

const data = {
  code: deleteField()
}

To delete a field from a Firestore document, call the deleteField() method as a value of it.

Call updateDoc() To Document Field

Invoke the updateDoc() method and pass docRef and data as arguments to it.

The updateDoc() method returns a promise so chain .then() and .catch() methods.

import {getFirestore, doc, updateDoc, deleteField} from "firebase/firestore";

const db = getFirestore();

const docRef = doc(db, "cities", "yftq9RGp4jWNSyBZ1D6L");

const data = {
    code: deleteField()
};

updateDoc(docRef, data)
.then(() => {
    console.log("Code Field has been deleted successfully");
})
.catch(() => {
    console.log(error);
})

When you run the updateDoc() query, the field name code will be removed from the Firestore document.

One more things it’s worth pointing out here is when you delete all the fields from a document, the document ID remains available in the collection and you can add a new field to the document.