How to add data with Custom ID to firestore?

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

-Above code generates ID automatically.

How to add data with Custom ID to firestore ? My purpose is to create a custom ID and write text data into this collection. Can,you help me ? Thank you.

1 Answers

As explained in the doc, you should use the set() method of the DocumentReference Class.

db.collection("users")
        .document("theIDYouWant")  // <== Specify the Doc ID here
        .set(user)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "DocumentSnapshot successfully written!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error writing document", e);
            }
        });
Related