关于documentId的Firestore集合组查询 [英] Firestore collection group query on documentId

查看:67
本文介绍了关于documentId的Firestore集合组查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的情况下,用户可以喜欢"另一位用户的个人资料.结果,我为每个用户创建了一个名为"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)-> User A(doc)-> LikedBy(col)-> User B(doc),User 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是array类型的属性.

Where usersWhoLikedMe is a property of type array.

这篇关于关于documentId的Firestore集合组查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆