DEV Community

Cover image for Firebase V9 Firestore DELETE Document Field Using updateDoc()
Raja Tamil
Raja Tamil

Posted on • Originally published at softauthor.com

Firebase V9 Firestore DELETE Document Field Using updateDoc()

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.

alt text

Import Firestore and d*e-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";


Enter fullscreen mode Exit fullscreen mode

Then, initialize the Firestore database.



const db = getFirestore(app);


Enter fullscreen mode Exit fullscreen mode

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");


Enter fullscreen mode Exit fullscreen mode

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()
}


Enter fullscreen mode Exit fullscreen mode

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);
})


Enter fullscreen mode Exit fullscreen mode

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

alt text

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.

Top comments (0)