How can I update more than 500 docs in Firestore using Batch?

后端 未结 3 1780
说谎
说谎 2020-12-03 05:56

I\'m trying to update a field timestamp with the Firestore admin timestamp in a collection with more than 500 docs.

const batch = d         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 06:42

    I also ran into the problem to update more than 500 documents inside a Firestore collection. And i would like to share how i solved this problem.

    I use cloud functions to update my collection inside Firestore but this should also work on client side code.

    The solution counts every operation which is made to the batch and after the limit is reached a new batch is created and pushed to the batchArray.

    After all updates are completed the code loops through the batchArray and commits every batch which is inside the array.

    It is important to count every operation set(), update(), delete() which is made to the batch because they all count to the 500 operation limit.

    const documentSnapshotArray = await firestore.collection('my-collection').get();
    
    const batchArray = [];
    batchArray.push(firestore.batch());
    let operationCounter = 0;
    let batchIndex = 0;
    
    documentSnapshotArray.forEach(documentSnapshot => {
        const documentData = documentSnapshot.data();
    
        // update document data here...
    
        batchArray[batchIndex].update(documentSnapshot.ref, documentData);
        operationCounter++;
    
        if (operationCounter === 499) {
          batchArray.push(firestore.batch());
          batchIndex++;
          operationCounter = 0;
        }
    });
    
    batchArray.forEach(async batch => await batch.commit());
    
    return;
    

提交回复
热议问题