簡體   English   中英

如何批量刪除 Firebase 雲 function 中的 Firestore 文檔

[英]How to do a Batch delete Firestore Documents in a Firebase cloud function

我正在使用 firebase 觸發器,當刪除某個文檔時,我可以使用 firebase 雲 ZC1C425268E68385D1AB5074C17A94 獲取我希望刪除的文檔集合的路徑。 到目前為止,我的 onDelete function 工作非常頭痛。

在觸發器上,我得到了我需要獲取要刪除的集合的路徑的 id,然后我使用 .get() 從集合中檢索文檔
然后我使用 forEach 來獲取我想要刪除的所有文檔。

我的問題是我想使用批量刪除,因為我已經閱讀了這是最好的方法,因為如果您有超過 500 個文檔要刪除,除非您使用批量刪除,否則您可能會遇到錯誤

所以當我遍歷文檔時,我使用 batch.delete(document.id),然后在循環之外我調用 batch.commit()

當 function 被觸發時,我在終端中收到此消息

⚠  Your function was killed because it raised an unhandled error.
i  functions: Beginning execution of "onDeleteTriggers"
>  the doc that We need to delete is  KLvuLSa1uSsVjaKmVOB5
>  ahOh there was an error deleting the documents
i  functions: Finished "onDeleteTriggers" in ~1s

我的完整代碼如下

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { firestore } = require("firebase-admin");
admin.initializeApp();

 exports.onDeleteTriggers = functions.firestore.document('recentMsg/currentuid/touid/{documentId}').onDelete(async(snap, context) => {
     const params = context.params     
     const db = admin.firestore();
     const batch = db.batch()

     await admin.firestore().collection(`messages/currentuid/${params.documentId}`)
     .get()
     .then(snap => {  
       snap.forEach(document => {
         console.log(`the doc that We need to delete is  ${document.id}`)
        
        //this takes in the documents i want to delete 
          batch.delete(document.id);
       })
      // then commit them 
       batch.commit();
     })
     .catch(functionCalledToHandleError)
    
})


function functionCalledToHandleError() {
  console.log('ahOh there was an error deleting the documents')
}



我對 firebase 雲功能非常陌生,所以我只是繼續我讀過的內容,因為我是新手,所以我覺得很難。 任何幫助將不勝感激

嘗試使用此 function 刪除集合:

async function deleteCollection(db, collectionPath, batchSize = 100) {
  const collectionRef = db.collection(collectionPath);
  const query = collectionRef.orderBy("__name__").limit(batchSize);

  return new Promise((resolve, reject) => {
    deleteQueryBatch(db, query, resolve).catch(reject);
  });
}

async function deleteQueryBatch(db, query, resolve) {
  const snapshot = await query.get();

  const batchSize = snapshot.size;
  if (batchSize === 0) {
    // When there are no documents left, we are done
    resolve();
    return;
  }

  // Delete documents in a batch
  const batch = db.batch();
  snapshot.docs.forEach((doc) => {
    batch.delete(doc.ref);
  });
  await batch.commit();

  // Recurse on the next process tick, to avoid
  // exploding the stack.
  process.nextTick(() => {
    deleteQueryBatch(db, query, resolve);
  });
}

export { deleteCollection, deleteQueryBatch };

我建議將其存儲到一個文件中,以便您可以在需要時在另一個 function 中重復使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM