Writing more than 500 data items in Firestore with Batch
1 min readJul 4, 2022
Writing more than 500 data items in Firestore with Batch
`batch()` has a limit of no more than 500 data items that can be written at one time.
If you try to write more than 500 items at once, it will fail.
Of course, the behavior of failure is not that it succeeds in writing 1~500 items and fails in writing more than 500 items, but that it fails in writing all items.
Writing more than 500 posts
If there are more than 500 items, the data is divided and written.
The following is a sample of how to divide and write data.
const followerList = follower.docs;const batchArray: FirebaseFirestore.WriteBatch[] = [];
batchArray.push(db.batch()!);
let operationCounter = 0;
let batchIndex = 0;followerList.forEach(async (doc: FirebaseFirestore.DocumentSnapshot) => {
const timelineDoc = db
.collection("timeline")
.doc(doc.id);
batchArray[batchIndex].set(timelineDoc, copyedData);
operationCounter++;if (operationCounter === 499) {
batchArray.push(db.batch());
batchIndex++;
operationCounter = 0;
}
});batchArray.forEach(async batch => await batch.commit());