Home > Back-end >  Could I set custom ID in firestore?
Could I set custom ID in firestore?

Time:11-04

Before, I used real-time DB, but now I need to change to use firestore.

when I doing writing data in real-time DB, I using this methods.

FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("email", email);
hashMap.put("username", username);

So the data will show like this

  "Users" : {
    "02nfE2JziDgzxZwYpmCwQ20QwQ93" : {
      "email" : "[email protected]",
      "id" : "02nfE2JziDgzxZwYpmCwQ20QwQ93",
      "username" : "AAA"
    },

But when I use firestore, it's will show this

  "Users" : {
    "u93AclSJJiLQBdfcK2st" : {
      "email" : "[email protected]",
      "id" : "02nfE2JziDgzxZwYpmCwQ20QwQ93",
      "username" : "AAA"
    },

Could I change u93AclSJJiLQBdfcK2st to 02nfE2JziDgzxZwYpmCwQ20QwQ93, if it's can change it, how do I do?

this is my code.

db = FirebaseFirestore.getInstance();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("email", email);
hashMap.put("username", username);

db.collection("Users").add(hashMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(RegisterActivity.this, "OK", Toast.LENGTH_SHORT).show();
   }
});

CodePudding user response:

When you call add() Firestore generates a new document ID. It is the equivalent of calling push() for the Realtime Database API.

If you want to specify your own document ID, don't call add but pass use document("yourNewId").set() instead:

db.collection("Users").document(userid).set(hashMap)...

Also see the Firebase documentation on setting a document value.

  • Related