对 documentId 的 Firestore 集合组查询 [英] Firestore collection group query on documentId
问题描述
在我的场景中,用户可以喜欢"另一个用户的个人资料.因此,我为每个用户创建了一个名为likedBy"的子集合,我在其中为特定用户创建了一个文档,例如:
In my scenario a user can "like" the profile of another user. As a result I have a subcollection called "likedBy" for each user, where I create a document for a specific user, e.g.:
users(col) -> 用户 A(doc) -> likeBy(col) -> 用户 B (doc), 用户 C (doc)
users(col) -> User A(doc) -> likedBy(col) -> User B (doc), User C (doc)
所以在极少数用户被删除的情况下,我想删除该用户的所有赞问题.
So in the rare scenario of a user being deleted, I want to delete all the likes issues by that user.
我只是不确定这是否可行(解决方法可能是在所述文档中再次保存 userId 并查询).
I am just not sure if this is even possible (a workaround could be to just save the userId again in said document and query for that).
我基本上要寻找的是这样的:
What I am basically looking for is something like this:
db.collectionGroup('likedBy').where(firebase.firestore.FieldPath.documentId(), '==', "User A").get();
问题是,我无法在 Firestore 控制台中为 documentId 创建索引.
The problem is, that I can not create an index for the documentId in the Firestore console.
推荐答案
您无法使用以下查询:
db.collectionGroup('likedBy').where(firebase.firestore.FieldPath.documentId(), '==', "User A").get();
这是因为集合组查询仅适用于文档属性,不适用于文档 ID.根据关于集合组查询的官方文档:
And this is because collection group queries work only on document properties and not on document ids. According to the official documentation regarding collection group queries:
db.collectionGroup('landmarks').where('type', '==', 'museum');
您查询 landmarks
子集合,其中 type
属性保存了 museum
的值.
You query the landmarks
subcollection where the type
property holds the value of museum
.
一种解决方法可能是将用户的 id 存储在一个数组中并使用 array-contains
但请记住,对于您使用的每个集合组查询,您都需要一个索引,但不幸的是您无法创建这样的以编程方式建立索引.即使您可以在 Firebase 控制台中创建索引,它也无济于事,因为您是动态获取这些 id 的.所以不是为每个用户单独创建索引的选项,因为您将达到 最大数量索引非常快.
A workaround could be to store the id of the user in an array and use array-contains
but remember, for each collection group query you use, you need an index and unfortunately you cannot create such an index programmatically. Even if you can create an index in the Firebase console, it won't help you since you get those ids dynamically. So is not an option to create an index for each user separately because you'll reach the maximim number of indexes very quickly.
一个数据库的最大复合索引数:200
Maximum number of composite indexes for a database: 200
要解决此类问题,您应该考虑在每个用户对象下添加一个数组并使用如下查询:
To solve this kind of problems, you should consider adding an array under each user object and use a query like this:
usersRef.where("usersWhoLikedMe", "array-contains", "someUserId")
其中 usersWhoLikedMe
是数组类型的属性.
Where usersWhoLikedMe
is a property of type array.
这篇关于对 documentId 的 Firestore 集合组查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!