Home > Software engineering >  Delete multi docs inside a collection in firestore?
Delete multi docs inside a collection in firestore?

Time:03-06

I have an array of ids which in my case represent documents inside a collection, my goal is to remove all of those those docs inside a collection according to id's inside an array my question is should I do a for loop on the doc delete function ? or is there a function that allows you to delete multi docs according

  const DeletAccount = async (sharedId: string, clientsIds: string[]) => {
    const batch = writeBatch(db);
    clientsIds.forEach((docId) => {
      batch.delete(doc(db, 'col1', docId));      
    });
    // Commit the batch
    await batch.commit();
    
    // Delete col2
    await deleteDoc(doc(db, 'col2', sharedId));
    // Delete Main doc col3
    await deleteDoc(doc(db, 'col3', currentUser.uid));
    }

const toDelete = ['sdferwer32423asd','Pasdas34234235', 'aMNsdasd21312223232']

to a preference like an array of ids in my case ?

CodePudding user response:

There isn't any deleteMany() function but you can try using Batched Writes to delete upto 500 documents in a single batch.

import { writeBatch, doc } from "firebase/firestore"; 

const toDelete = ['sdferwer32423asd','Pasdas34234235', 'aMNsdasd21312223232']

const batch = writeBatch(db);

toDelete.forEach((docId) => {
  batch.delete(doc(db, "collectionName", docId))
}) 

// Commit the batch
await batch.commit();

Alternatively, you can map an array of promises and then use Promise.all() as shown below:

const promises = toDelete.map((docId) => deleteDoc(doc(db, "collection", docId)))

await Promise.all(promises)

The delete() in a batch just requires a DocumentReference so you can delete documents from multiple collections as shown below:

// After forEach in previous code snippet

await batch.delete(doc(db, 'col2', sharedId));
await batch.delete(doc(db, 'col3', currentUser.uid));

// Batch commit at the end
batch.commit();
  • Related