Reputation: 1
I have a number in the usersnumber collection (counter document), and I want to take that number and put it in the users collection in the number field (as you can see in the photo). Is there any way I can get the data from usersnumber and update the users > collection > document > number?
I expect having the number 10 from the usersnumber collection in the collection users > document > number: 0
Upvotes: 0
Views: 531
Reputation: 18585
a transaction is a set of read and write operations on one or more documents.
Using the Cloud Firestore client libraries, you can group multiple operations into a single transaction. Transactions are useful when you want to update a field's value based on its current value, or the value of some other field.
https://firebase.google.com/docs/firestore/manage-data/transactions#transactions
import { runTransaction } from "firebase/firestore";
try {
await runTransaction(db, async (transaction) => {
const sfDoc = await transaction.get(sfDocRef);
if (!sfDoc.exists()) {
throw "Document does not exist!";
}
const newPopulation = sfDoc.data().population + 1;
transaction.update(sfDocRef, { population: newPopulation });
});
console.log("Transaction successfully committed!");
} catch (e) {
console.log("Transaction failed: ", e);
}
Upvotes: 1