javascriptfirebasegoogle-cloud-platformgoogle-cloud-firestore

Can we update a field due to its value without reading it in firebase?


In firebase, can we update a field due to its value without reading it (without having a local copy)? For example, I have a doc with points field which is equal to 5. I want to add 1 to the points field. Is there a way to update it with updateDoc(doc(db, ... )) without reading first with getDoc?


Solution

  • For numeric fields, you can use the increment operation for that. In modular JavaScript that's:

    import { doc, updateDoc, increment } from "firebase/firestore";
    
    const washingtonRef = doc(db, "cities", "DC");
    
    // Atomically increment the population of the city by 50.
    await updateDoc(washingtonRef, {
        population: increment(50)
    });
    

    For more examples, see the documentation on Google Cloud: Increment a Firestore document field and Firebase's documentation: Increment a numeric value (that's where I got the above example from).