首页 > 解决方案 > Firestore 查询 Array 子集合

问题描述

我

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

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

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

标签: androidgoogle-cloud-firestore

解决方案


要以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文档中的数组而不是集合一样。

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


推荐阅读