删除嵌套集合中的文档

Deleting document inside a nested Collection

我正在创建一个函数来清除嵌套集合中的所有文档。我已经按如下方式访问它。

const deleteChat = async () => {

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

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

我该怎么做?这 doc.data() returns messages 集合中的数据。我试过使用其他解决方案,但没有用。帮助将不胜感激:)

get() 从该集合中读取所有文档。您需要使用 delete() 来删除文档。尝试重构代码,如下所示:

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")
};

这里chatSnapShot.docsQueryDocumentSnapshot 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()

的数组

您还可以使用 batched writes.

批量删除文档,最多 500 个文档