Firebase Cloud Firestore获取新创建文档的自动ID [英] Firebase Cloud Firestore get auto-id of newly created document

查看:98
本文介绍了Firebase Cloud Firestore获取新创建文档的自动ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码创建了一个用户,但是由于该用户的Document ID是随机生成的,因此我希望在创建DocumentReference之后将其存储在变量中.我该怎么办?

I have created a user with the following code, however since the Document ID of the user is randomly generated, I would like to store the DocumentReference in a variable after it has been created. How could I do this?

FirebaseFirestore db = FirebaseFirestore.getInstance();

// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("username", "username");
user.put("first", "Firstname");
user.put("last", "Lastname");
user.put("born", 1990);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());

            }

        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
                return null;
            }
        });

推荐答案

由于add()是异步的并立即返回,因此您应该期望通过提供的成功侦听器对结果DocumentReference进行任何操作. .尝试为本地变量分配某些内容可能不会有帮助,因为调用add()的方法的其余代码几乎肯定会在调用回调时完成.

Since add() is asynchronous and returns immediately, you should expect to do anything with the resulting DocumentReference via the success listener you provided. Attempting to assign something to a local variable will not likely be helpful, because the rest of the code your method that invoked add() will almost certainly be complete by the time the callback is invoked.

如果要立即获得随机文档ID,请在实际创建文档之前,使用不带参数的document()代替add().这将为尚未创建的随机文档(已分配了ID)提供一个DocumentReference.然后可以随时准备set().

If you want a random document ID immediately, before the document is actually created, use document() with no parameters instead of add(). This will get you a DocumentReference for a random document not yet created, which already had an ID assigned. Then you can set() that whenever you're ready.

这篇关于Firebase Cloud Firestore获取新创建文档的自动ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆