Firebase Cloud Firestore get auto-id of newly crea

2019-06-14 04:23发布

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;
            }
        });

2条回答
女痞
2楼-- · 2019-06-14 04:43

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.

查看更多
地球回转人心会变
3楼-- · 2019-06-14 04:43

Since you are creating the document under users folder, your document reference should be combination of user folder and document id

db.collection("users").document(documentReference.getId())
查看更多
登录 后发表回答