【问题标题】:How to get DocumentSnapshot id as String?如何获取 DocumentSnapshot id 作为字符串?
【发布时间】:2019-02-27 21:35:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: java android google-cloud-firestore


    【解决方案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());
                    }
                }
            });
    

    【讨论】:

    • 其实这还不是我想要的。我想在一个字符串上打开 documentSnaphot id,这样我就可以将它保存在另一个集合 @JRLtechwriting 上。这就像在 Firebase 上获取密钥
    • 当然,只是需要更多上下文。您是否已经知道文档的文档 ID?或者您知道它包含的唯一字段值吗?
    • 是的。你的代码效果很好。我想我可以很好地解释。看我的帖子,看看你能不能看懂stackoverflow.com/questions/54897811/…
    猜你喜欢
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多