Twitter LogoFacebook Logo
How to Update Data in Firestore
Learn how to update an existing document in the Firestore database using FirebaseTS
By: King

To update an existing document in Firestore, first you must add the FirebaseTS library to your project. Follow this tutorial to learn how to add FirebaseTS.

Once you have added FirebaseTS, you are set to go!

How to update an document in Firestore

Updating a document

In this section, we will be updating the data of an existing document in Firestore using the update() method from the FirebaseTSFirestore Class.

Here is the definition of the update() method.

public update<DT>(
    params: {
        poth: string [], 
        data: DT, 
        onComplete?: (docRef: firebase.firestore.DocumentReference) => void,
        onFail?: (err: any) => void
    }): Promise<firebase.firestore.DocumentReference>;

path - is an string array that points to a document in Firestore. The first element will be the collection and the second element will be the document id. The array can only point to a document id or it will throw an error.

[

  "UserCollection",
  "User1Document",
  "Contacts",
  "Mom"
]

The first element of the array points to a collection and the second points to a document and the pattern repeats itself if more elements are added.


data - the data that is to be updated for the document. It is in a form of a JSON object.

For example:

{
  age: 64
}

This will update the age property to 64. If the property do not exist, it will append the existing data.

onComplete?: docRef: => void - is an optional callback function that allows you to handle logic after the task is completed.

onFail?: err => void - is an optional callback function that allows you to handle logic when it was not able to update the document.

How to use

1. Import the FirebaseTSFirestore class.

import FirebaseTSFirestore from 'firebasets/firebasetsFirestore/firebaseTSFirestore';

2. Declare and initialize a FirebaseTSFirestore object.

private firestoreFirebaseTSFirestore;

constructor(){
  this.firestore new FirebaseTSFirestore();
}

3. Call the update() method.

this.firestore.update(
 {
   path: [
     "UserCollection",
     "User1Document"
   ],
   data: {
     age: 64
   }
 }
);

Here, we updated the document age property from "User1Document" in the "UserCollection" collection.

Handling code on complete or fail

Sometimes you may want to do something when you have successfully or unsuccessfully updated data for a document, like a notification message. You can add the optional parameters onComplete and onFail.

this.firestore.create (
 {
   path: [ ... ],
   data: { ... },
   onComplete: docRef=> {
      // Code gets executed when it was successful.
      alert("Data updated!");
   },
   onFail: err => {
      // Code gets executed when it fails.
      alert(err.message);
   }
 }
);


Sign In