Firestore delete document and all documents referencing it

你。 提交于 2020-08-26 13:42:26

问题


this question is regarding Firebase (+ Flutter)

is it possible to delete a document and all documents referencing it?

Lets assume i have a structure like this:

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

Now if i delete a post, i want to delete all bookmarks referencing that post. (From all users). Is there an automatic way (coming from RDBMS).

Another question: How can i query all posts and "join" the user infos.

Something like this:

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

And are these nested queries then and counting to the api limit?

Thanks in advance


回答1:


you have to query the docs and then batch delete them. i don't use subcollections, and i'm not going to look up how to query them, but with a root level schema you'd delete the post with a standard firestore delete, referencing the documentID. assuming the documentID is the same as your 'postID' field (and if it isn't, refactor your schema) you'd then:

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();

be aware that batches can only be done 500 at a time:

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

so you'd have to split up your _batch.commit() calls as necessary.




回答2:


There is no automatic method to do what you want. Firestore isn't a relational database, so relationships between documents are not enforced. There are no "join" operations in Firestore.

You could instead query for the documents to delete, the delete them all after you iterate the query results.



来源:https://stackoverflow.com/questions/52048204/firestore-delete-document-and-all-documents-referencing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!