Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore transaction update multiple documents in a single transaction

Tags:

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.

like image 895
suhail c Avatar asked Nov 28 '17 13:11

suhail c


2 Answers

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.

like image 71
suhail c Avatar answered Sep 20 '22 15:09

suhail c


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(); }; 
like image 32
Raunak Agrawal Avatar answered Sep 20 '22 15:09

Raunak Agrawal