Home > Net >  get and update value at once in firebase
get and update value at once in firebase

Time:07-10

How to get value from firebase document and update it imediatelly?

I know how to update document, and how to get document values, but how can i read and update this value at once?

update

firebase.firestore().collection("colection").doc('document').set(
 {
      value: value   10

  }, { merge: true })

get

firebase.firestore().collection("colection").doc("document").get().then((doc) => {
        if (doc.exists) {
            console.log("Document data:", doc.data().value);
        } else {
            console.log("No such document!");
        }
    }).catch((error) => {
        console.log("Error getting document:", error);
    });

CodePudding user response:

To read-and-update a document atomically, you'll want to use a transaction. From that documentation comes this example:

// Create a reference to the SF doc.
var sfDocRef = db.collection("cities").doc("SF");

// Uncomment to initialize the doc.
// sfDocRef.set({ population: 0 });

return db.runTransaction((transaction) => {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(sfDocRef).then((sfDoc) => {
        if (!sfDoc.exists) {
            throw "Document does not exist!";
        }

        // Add one person to the city population.
        // Note: this could be done without a transaction
        //       by updating the population using FieldValue.increment()
        var newPopulation = sfDoc.data().population   1;
        transaction.update(sfDocRef, { population: newPopulation });
    });
}).then(() => {
    console.log("Transaction successfully committed!");
}).catch((error) => {
    console.log("Transaction failed: ", error);
});
  • Related