Skip to content Skip to sidebar Skip to footer

Return All Docs When All Docs Are Deleted In A Collection In Firestore

I am using the code below to remove all docs in a collection in Firestore. My question is, how to execute a function which will return the result (promise) of 'deleteCollection' am

Solution 1:

First of all, avoid the Promise constructor antipattern:

functiondeleteCollection(db, collectionRef, batchSize) {
  var query = collectionRef.limit(batchSize);
  returndeleteQueryBatch(db, query, batchSize);
}

functiondeleteQueryBatch(db, query, batchSize) {
  return query.get().then(snapshot => {
    if (snapshot.size == 0) return0;
    var batch = db.batch();
    snapshot.docs.forEach(doc => { batch.delete(doc.ref); });
    return batch.commit().then(() => snapshot.size);
  }).then(function(numDeleted) {
    if (numDeleted >= batchSize) {
      // I don't think process.nextTick is really necessaryreturndeleteQueryBatch(db, query, batchSize);
    }
  });
}

(You might also want to use async/await syntax which really simplifies the code and makes the algorithm better understandable:

async function deleteQueryBatch(db, query, batchSize) {
  const snapshot = await query.get();
  if (snapshot.size > 0) {
    let batch = db.batch();
    snapshot.docs.forEach(doc => { batch.delete(doc.ref); });
    await batch.commit();
  }
  if (snapshot.size >= batchSize) {
    // await new Promise(resolve => process.nextTick(resolve));return deleteQueryBatch(db, query, batchSize);
  }
}

creating a empty global variable in which the delete function adds the doc. But how safe is this? If I am deleting two huge collections, the array gets populated with two different docs. That wouldn't be correct as well.

No, don't do this. Just pass the array that you're populating with the results as an argument through the recursive calls and return it in the end:

functiondeleteCollection(db, collectionRef, batchSize) {
  returndeleteQueryBatch(db, collectionRef.limit(batchSize), batchSize, []);
}
asyncfunctiondeleteQueryBatch(db, query, batchSize, results) {
  const snapshot = await query.get();
  if (snapshot.size > 0) {
    let batch = db.batch();
    snapshot.docs.forEach(doc => {
      results.push(doc);
      batch.delete(doc.ref);
    });
    await batch.commit();
  }
  if (snapshot.size >= batchSize) {
    returndeleteQueryBatch(db, query, batchSize, results);
  } else {
    return results;
  }
}

Post a Comment for "Return All Docs When All Docs Are Deleted In A Collection In Firestore"