Firestore 集合组查询文档 ID [英] Firestore collection group query on document id

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

问题描述

我正在尝试运行以下查询:

I am trying to run the following query:

this.db.firestore
        .collectionGroup('members')
        .orderBy('dateModified', 'desc')
        .where(firebase.firestore.FieldPath.documentId(), '==', uid)

但我收到错误:

无效查询.查询集合组时FieldPath.documentId(),提供的值必须产生一个有效的文档路径,但 'X6yL5Ko55jSMWhhoQUO91xVYdEH3' 不是因为它具有奇数个段 (1).

Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but 'X6yL5Ko55jSMWhhoQUO91xVYdEH3' is not because it has an odd number of segments (1).

是将文档ID 添加到文档的唯一方法吗?这并不理想,因为我有很多现有数据......文档 ID 是 firebase 用户的 uid.

Is the only way around this to add the document id to the document? This is not ideal as I have a lot of existing data... The document id is the uid of the firebase user.

推荐答案

uid 添加到文档本身是目前唯一可行的方法,然后对该字段进行查询:

Adding the uid to the document itself is the only possible way at the moment and then query on that field:

this.db.firestore
        .collectionGroup('members')
        .orderBy('dateModified', 'desc')
        .where("uid", '==', uid)

Github 问题相同并解释了为什么这是不可能的.

There was a Github issue for the same and explains why that's not possible.

这就是为什么我有时更喜欢存储根级集合成员的原因.集合中的每个文档都将包含 groupID(或任何您的父集合的用途).如果您使用用户 ID 作为其中文档的键,那么事情就变得简单了.

That's pretty much why I sometimes prefer to store a root level collection members. Each document in the collection will have contain the groupID (or whatever your parent collection is meant for). If you use userID as the key for documents in there then it goes easy.

this.db.firestore.collection("members").doc(uid)

因此,与路径类似:/groups/{groupID}/members/{memberID},结构将类似于:/groups/{groupID}并且所有成员都将存储在根级别集合成员"中.该集合中的文档可能如下所示:

So instead of having a path like: /groups/{groupID}/members/{memberID}, the structure will be like: /groups/{groupID} and all the members will be store in the root level collection 'members'. A document in that collection may look like:

// uid as doc key
{
  groupId: "groupID", 
  ...otherFields
}

问题是,如果一个成员可以加入多个组,则不能使用 userId 作为键.

The catch is if a member can join multiple groups you cannot use the userId as the key.

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

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