【问题标题】:Could I set custom ID in firestore?我可以在 Firestore 中设置自定义 ID 吗?
【发布时间】:2021-12-18 00:48:44
【问题描述】:

之前我使用实时数据库,但现在我需要更改为使用firestore。

当我在实时数据库中写入数据时,我使用这种方法。

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

所以数据会这样显示

  "Users" : {
    "02nfE2JziDgzxZwYpmCwQ20QwQ93" : {
      "email" : "sowtp12pushcivet@gmail.com",
      "id" : "02nfE2JziDgzxZwYpmCwQ20QwQ93",
      "username" : "AAA"
    },

但是当我使用firestore时,它会显示这个

  "Users" : {
    "u93AclSJJiLQBdfcK2st" : {
      "email" : "sowtp12pushcivet@gmail.com",
      "id" : "02nfE2JziDgzxZwYpmCwQ20QwQ93",
      "username" : "AAA"
    },

我可以将u93AclSJJiLQBdfcK2st 更改为02nfE2JziDgzxZwYpmCwQ20QwQ93,如果可以更改,我该怎么做?

这是我的代码。

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

【问题讨论】:

    标签: android firebase-realtime-database google-cloud-firestore


    【解决方案1】:

    当您调用add()时,Firestore 会生成一个新的文档 ID。这相当于为实时数据库 API 调用 push()。

    如果您想指定自己的文档 ID,请不要调用 add,而是通过使用 document("yourNewId").set():

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

    另请参阅 setting a document value 上的 Firebase 文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 2018-07-27
      相关资源
      最近更新 更多