Home > Enterprise >  Deleting document inside a nested Collection
Deleting document inside a nested Collection

Time:03-27

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 :)

CodePudding user response:

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.

  • Related