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

Deleting document inside a nested Collection

I was making a function to clear all documents inside a nested collection. I’ve accessed it as follow.

const deleteChat = async () => {

  const chatSnapShot = await db
    .collection("chats")
    .doc(router.query.id)
    .collection("messages")
    .get();

  chatSnapShot.forEach((doc) => {
    console.log(doc.data());
  });
};

How can I do that? This doc.data() returns the data inside the messages collection. I’ve tried using other solutions but things doesn’t work. Help would be appreciated 🙂

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 :

The get() reads all documents from that collection. You need to use delete() to delete a document. Try refactoring the code as shown below:

const deleteChat = async () => { 
  const chatSnapShot = await db
    .collection("chats")
    .doc(router.query.id)
    .collection("messages")
    .get();

  const deletePromises = chatSnapshot.docs.map(d => d.ref.delete());

  await Promise.all(deletePromises)
  console.log("Documents deleted")
};

Here chatSnapShot.docs is an array of QueryDocumentSnapshot and you can get DocumentReference for each doc using .ref property. Then the doc reference has .delete() method to delete the document. This method returns a promise so you can map an array of promises and run them at once using Promise.all()


You can also delete documents in batches of up to 500 documents using batched writes.

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