Last active
July 21, 2023 10:55
-
-
Save MorenoMdz/516c590f2a034bf39c55708574831da8 to your computer and use it in GitHub Desktop.
Firebase Firestore batch more than 500 docs or operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const batchWrapper = async (documentRef, action, update) => { | |
const batchArray = []; | |
batchArray.push(db.batch()); | |
let operationCounter = 0; | |
let batchIndex = 0; | |
documentRef.forEach(doc => { | |
console.log('Org cleanup: deleting notifications', doc.id); | |
if (action === 'delete') { | |
batchArray[batchIndex].delete(doc.ref); | |
} | |
if (action === 'update') { | |
batchArray[batchIndex].update(doc.ref, update); | |
} | |
operationCounter++; | |
if (operationCounter === 499) { | |
batchArray.push(db.batch()); | |
batchIndex++; | |
operationCounter = 0; | |
} | |
}); | |
batchArray.forEach(async batch => await batch.commit()); | |
return; | |
}; | |
const clearOrganizationData = async organizationId => { | |
const usersRef = await db | |
.collection('users') | |
.where('organizationId', '==', organizationId) | |
.get(); | |
const notificationsRef = await db | |
.collection('notifications') | |
.where('organizationId', '==', organizationId) | |
.get(); | |
const rewardsRef = await db | |
.collection('rewards') | |
.where('organizationId', '==', organizationId) | |
.get(); | |
await batchWrapper(usersRef, 'delete'); | |
await batchWrapper(rewardsRef, 'delete'); | |
await batchWrapper(notificationsRef, 'delete'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment