如何将DocumentSnapshot id作为String?

问题描述 投票:0回答:1

如何在Firestore中获取文档的ID?

final String PostKey = db.collection("Anuncio").document().getId();

我正在尝试这种方式,但它会返回一个新的id。如何获取已经退出的文档的ID?

java android google-cloud-firestore
1个回答
1
投票

如果您事先不知道文档ID,可以retrieve all the documents in a collection并打印出ID:

db.collection("Anuncio")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

如果您对文档的子集感兴趣,可以使用add a query clause过滤文档:

db.collection("Anuncio")
        .whereEqualTo("some-field", "some-value")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.