LoginSignup
11
6

More than 3 years have passed since last update.

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

Posted at

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

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

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

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

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6