Firestore删除子集合中的所有文档
在我的Cloud Firestore设置(iOS/Swift应用程序)中,我有一个Post
集合和一个Likes
子集合. Likes
子集合具有一个文档,其中包含喜欢该帖子的用户的信息,而documentID是喜欢者的用户ID.
In my Cloud Firestore setup (iOS/Swift app), I have a Post
collection with a Likes
subcollection. The Likes
subcollection has a document that contains the information of the user that liked that post, with the documentID being the userID of the liker.
当用户更新其帖子时,我想清除Likes
子集合(在我的应用中,该用户仅更新了一个帖子,而不是创建一个新帖子).
When the user updates their post, I want to clear the Likes
subcollection (in my app, the user just updates a post instead of creating a new one).
我已经读过,不建议删除子集合中的每个文档,所以我想知道如何才能做到这一点.受欢迎的用户可能有成千上万的喜欢,因此全部删除它们可能会耗资巨大.
I have read that deleting every document in a subcollection is not advised, so I am wondering how I can accomplish this. A popular user could have thousands and thousands of likes, so deleting them all could be costly.
据我了解,我可以使用Cloud Functions以某种方式完成此任务吗?我尝试阅读有关Cloud Functions的文章,但我正迷路了.有没有一种方法可以触发Cloud Function在更新其用户的帖子后删除该用户的Likes
子集合中的所有文档?
It's my understanding that I can accomplish this somehow using Cloud Functions? I tried reading up on Cloud Functions and I'm getting pretty lost. Is there a way I can trigger a Cloud Function to delete all the documents in the Likes
subcollection for that user upon updating their post?
在Cloud Functions中,您只是使用Firebase Admin SDK来访问Firestore.在Cloud Functions中运行该SDK不会获得任何神奇的额外API.
From Cloud Functions you're just using the Firebase Admin SDK to access Firestore. There is no magic extra APIs that you get from running that SDK in Cloud Functions.
无论是在客户端SDK还是在Admin SDK中,都无法一次性删除集合中的所有文档.有关更多信息,请参见:
There is no way to delete all documents from a collection in one go, neither in the client-side SDKs nor in the Admin SDK. For more on this, see:
- Deleting all documents in Firestore collection
- Why "single bulk" delete collection in Cloud Firestore is not possible like it is with Realtime Database? (which also explains the reason)
- Delete firestore collection (which points to using Cloud Functions as a custom API endpoint)