Deleting all documents in Firestore collection

后端 未结 7 816
我在风中等你
我在风中等你 2020-11-30 06:51

I\'m looking for a way to clear an entire collection. I saw that there is a batch update option, but that would require me to know all of the document IDs in the collection.

相关标签:
7条回答
  • 2020-11-30 07:19

    2020 updated answer

    You can do it with Node JS - (notice they used process which is a famous object in node not available in Web javascript)

    Look at this snippet on Github hosted by firebase. I always had that page pinned to my browser ;)

    // [START delete_collection]
    
    async function deleteCollection(db, collectionPath, batchSize) {
      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);
      });
    }
    
    // [END delete_collection]
    
    0 讨论(0)
提交回复
热议问题