How can i update multiple documents in firestore by using a single transaction i searched but i didn't get any answers. Is it possible to update multiple documents in a single transaction? I know it can be done by batch writes.
I figured it out we can use multiple ref inside a transaction:
var userSuhail = db.collection("users").doc("suhail"); var userSam = db.collection("users").doc("sam"); var userJohn = db.collection("users").doc("john"); var userAlfred = db.collection("users").doc("Alfred"); var userAlfredDetails = db.collection('userdetails').doc('Alfred'); db.runTransaction(function (transaction) { return transaction.get(userJohn).then(function (sDoc) { var age = sDoc.data().age + 1; transaction.set(userAlfred, { name: 'Alfred', age, details: userAlfredDetails, }); transaction.set(userAlfredDetails, { address: 'Alfred Villa', }); transaction.update( userJohn , { age, }, ); transaction.update( userSuhail , { age, }, ); transaction.update( userSam , { age, }, ); return age; }); }).then(function (age) { console.log("Age changed to ", age); }).catch(function (err) { console.error(err); });
By the above code the transaction updates age of all users.
You can use batch method which firebase provides. This is how I used it to store array of objects, creating multiple documents inside a newly created collection.
export const addCollectionAndDocuments = async (collectionKey, objectToAdd) => { console.log(collectionKey, objectToAdd); let collectionRef = firestore.collection(collectionKey); const batch = firestore.batch(); objectToAdd.forEach(obj => { const newDocRef = collectionRef.doc(); batch.set(newDocRef, obj); }); return await batch.commit(); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With