Firestore transaction update multiple documents in a single transaction
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();
};