【问题标题】:Firestore to query Array sub collectionFirestore 查询 Array 子集合
【发布时间】:2021-06-27 08:33:06
【问题描述】:

我的 Firestore 集合结构如图所示。 Following 是主集合名称,其中包含当前记录的 userId 作为文档(“AuScbj..”) 其中包含一个名为 uIds 的子集合,其中包含他关注的用户的用户 ID。

当登录用户(“AuScbj..”)访问特定用户个人资料时,我如何通过如下查询来检查该个人资料用户的 ID 是否在他的以下列表中可用

firebaseFirestore.collection("Following)
.document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.collection("uIds").where(

【问题讨论】:

  • 所以基本上你要检查登录用户“AUScbTj5MpNY..”ID是否已经存在于所有用户的uIds数组中吧?
  • “AUScbTj5MpNY..”后面的所有其他用户都将添加到uIds数组(id1,id2)中,因此当“AUScbTj5MpNY..”访问特定用户配置文件(id1)时,它将检查id1是否在他的 uIds 数组中可用,如果可用,该配置文件在“AUScbTj5MpNY..”前面被标记为跟随

标签: android google-cloud-firestore


【解决方案1】:

您正在寻找.where(fieldPath: "uids", opStr: "array-contains", value: followingUID)。它应该适用于您的简单“数组”数据。

【讨论】:

  • 所以 firebaseFirestore.collection("Following) .document(FirebaseAuth.getInstance().getCurrentUser().getUid()) .collection("uIds").where(fieldPath: "uids", opStr : "array-contains", value: followingUID) 对吗?我可以将 uIds 称为子集合,如 ...collection("uIds")
  • “数组”和集合/子集合完全不同。 firebaseFirestore.collection("Following) .document(FirebaseAuth.getInstance().getCurrentUser().getUid())where(fieldPath: "uids", opStr: "array-contains", value: followingUID)
【解决方案2】:

要以非常简单的方式检查 id1 是否存在于 uIds 数组中,首先,您应该创建一个类:

class Document {
    List<String> uIds;
}

然后获取“AUScbTj5MpNY..”文档,使用以下方法读取uIds数组的内容:

private void checkId(String id) {
    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    CollectionReference followingRef = rootRef.collection("Following");
    DocumentReference uidRef = followingRef.document(uid);
    uidRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    List<String> uIds = document.toObject(Document.class).uIds;
                    if (uIds.contains(id)) {
                        //Update the UI
                    }
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException());
            }
        }
    });
}

在 onComplete 中,我们将数组作为 List 获取,并检查我们调用方法所用的 id 是否存在于数组中。为了使它起作用,请使用以下命令开始:

checkId(id1);

另请注意:

firebaseFirestore.collection("Following)
    .document(FirebaseAuth.getInstance().getCurrentUser().getUid())
    .collection("uIds").where(/* ... /*);

永远不会起作用,因为uIds 是文档中的一个数组,而不是一个集合。

您还可以在以下文章中找到更多信息:

【讨论】:

  • 你觉得这个查询效率高吗?假设 uIds 有 1000 个项目,在您的方法中,您正在查询每条记录并对其进行过滤。我需要一种有效的方法。
  • 是的,绝对是高效的!这与数组中的项目数量无关,更多的是关于size of the document。因此,只要您将大小保持在 1MiB 限制以下,一切都会正常工作。
猜你喜欢
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 2020-07-26
相关资源
最近更新 更多