😀

Firestoreで500件以上のデータをBatchで書き込む

2020/09/16に公開

FirestoreのBatch()では一度に書き込めるデータ数は500件以下しか書き込めない制限があります。

500件以上一気に書き込みをやろうとすると、失敗になります。

当たり前ですが、失敗のときどういう挙動になるかというと、 1~500件は成功して、それ以上は失敗するみたいな挙動ではなく、 全ての書き込みに失敗します。

https://firebase.google.com/docs/firestore/manage-data/transactions?hl=ja

500件以上書き込みをする

では、どうやって500件以上を書き込みをするかという、 500件以上ある場合は、データを分割して書き込みを行います。

分割して、書き込むサンプルは下記です。


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());

Discussion