首页 > 解决方案 > Firestore 删除文档和引用它的所有文档

问题描述

这个问题是关于 Firebase (+ Flutter)

是否可以删除文档和引用它的所有文档?

假设我有这样的结构:

-users (collection)
  - name
  - bookmarks ((sub)collection)
    - postId
-post (collection)
  - userId
  - name
  - ...

现在,如果我删除一个帖子,我想删除所有引用该帖子的书签。(来自所有用户)。是否有自动方式(来自 RDBMS)。

另一个问题:我如何查询所有帖子并“加入”用户信息。

像这样的东西:

return firestore
        .collection("posts")
        .orderBy("createdAt")
        .snapshots(); // I want to join the userInformation

那么这些嵌套查询是否计入 api 限制?

提前致谢

标签: firebasedartfluttergoogle-cloud-firestore

解决方案


您必须查询文档,然后批量删除它们。我不使用子集合,也不会查找如何查询它们,但是使用根级别架构,您将使用标准的 Firestore 删除来删除帖子,并引用 documentID。假设 documentID 与您的“postID”字段相同(如果不是,请重构您的架构),您将:

final WriteBatch _batch = Firestore.instance.batch();

  QuerySnapshot _query = await dbUsers.where('postId', isEqualTo: thatDocumentID).getDocuments();

  _query.documents.forEach((doc) {
    _batch.delete(dbUsers.document(doc.documentID));
  });

  await _batch.commit();

请注意,批次一次只能完成 500 个:

https://firebase.google.com/docs/firestore/manage-data/transactions

所以你必须根据_batch.commit()需要分开你的电话。


推荐阅读