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.
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.
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();
};
Proof of concept:
var transaction = firestore.runTransaction( t => {
return t.get(eRef)
.then(snapshot => {
snapshot.forEach(doc => {
var employee = doc.data();
if(employee.status !== 'Off work') {
t.update(doc.ref, {
status: 'Off work',
returnTime: '8 am'
})
}
})
})
}).then(result => {
console.log('Transaction success!')
}).catch(err => {
console.log('Transaction failure: ', err)
});
you can use this =>
firestore.collection("YOUR_COLLECTION_PATH")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
Also if you want to map the querySnapshot in an array, you can do like this:
firestore.collection("YOUR_COLLECTION_PATH")
.get()
.then(function(querySnapshot) {
var arrayDocs = querySnapshot.docs.map(docData=>docData.data())
console.log(arrayDocs);
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
The info is at https://firebase.google.com/docs/firestore/query-data/get-data