Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete multi docs insde a collection in firestore?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading