Android Firestore搜索集合,其中document是唯一ID

时间:2018-02-17 15:00:16

标签: firebase google-cloud-firestore

Firestore是否可以检索文档名称未知或唯一ID的文档中的数据。就像链接图像一样。 ID未知,而名称已知,是否可以在此实例中获取ID? Database structure example

db.collection("users").document(??).collection("John Doe");

2 个答案:

答案 0 :(得分:1)

您将需要一个名称查询:

var peopleRef = db.collection("users");
// there may multiple users if there are more then one `John Doe`
peopleRef.where("name", "==", "John Doe")
.get()
.then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        //Here below will list all people who's name = "John Doe", If only one then this John Doe's  id no: doc.id as fallow:
        console.log(doc.id, " => ", doc.data());
    });
})
.catch(function(error) {
    console.log("Error getting documents: ", error);
});

答案 1 :(得分:1)

感谢HakanC的回答我稍微修改了一下以使其正常工作,如下所示。

CollectionReference peopleRef = mFirestore.collection("users");
    peopleRef.whereEqualTo("fullName", "John Doe")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });