Firebase:删除其中没有子集合的文档

Firebase: Delete documents without a subcollection inside them

我有一个名为“departments”的集合,里面有一个名为“users”的子集合。我想删除“部门”中没有用户子集合文档或没有子集合用户的所有文档。

关于如何找到要删除的文档有什么想法吗?

谢谢!

假设您的结构如下所示:

Firestore-root
  |
  --- departments (collection)
        |
        --- $departmentId (document)
               |
               --- users (collection)
                    |
                    --- $uid (document)
                         |
                         --- //user data

能够做到这一点:

I want to delete all the documents in "departments" without documents in the users sub-collection.

您必须获取 users sub-collection 中的所有文档并将其删除。但请记住,如果您的集合中有大量文档,Firebase 团队的此类操作 将在客户端上完成。但是,对于少量文档,它会起作用。

这个操作最重要的是,如果删除那些文件,sub-collection还会继续存在,而.

仅在实时数据库中,如果删除一个节点,则会删除该节点及其下存在的所有数据。但这里不是这样的,不用担心。

为了能够删除没有子集合的文档,您必须查询 departments 集合并迭代文档以检查它们是否包含子集合 users。请参阅下面的示例代码:

const db = getFirestore();

// `departments` reference.
const departmentsRef = query(collection(db, "departments"));
// Gets all documents from the department's reference.
const querySnapshot = await getDocs(departmentsRef);

// Iterate the documents.
querySnapshot.forEach(async (doc) => {

  // `users` reference.
  const usersRef = query(collection(db, "departments", doc.id, "users"));
  
  // Check if the document has the `users` collection
  const querySnapshot = await getDocs(usersRef)
  .then((usersDoc) => {
    
    // Check if the `users` subcollection exists
    // Also counts the documents of the subcollection. 
    if (!usersDoc.size) {
      // Deletes the document from the document reference.
      deleteDoc(doc.ref);
    }
  });
});