2 回答

TA貢獻1799條經驗 獲得超6個贊
每次您撥打電話時document()
,您都會獲得一個新的唯一 ID。因此,請務必只調用一次,這樣您就只處理一個 ID。
首先獲取文檔參考:
DocumentReference ref = db.collection("user_details").document();
獲取其ID:
String id = ref.getId();
然后編寫要發送的數據:
Map map = new HashMap<>(); map.put("username", username); map.put("email", email); map.put("id", id);
最后,將該數據放入前面引用的文檔中:
ref.set(map)...

TA貢獻2011條經驗 獲得超2個贊
為了能夠將您的 ID 保存在文檔中,您首先需要創建一個文檔。問題是 ID 是在創建文檔的同時創建的。但我們可以首先創建 ID,然后像這樣發送我們的文檔:
val matchRef = mFirestore.collection(FirebaseHelp().USERS).document(user.uid).collection(FirebaseHelp().MATCHES).document() //notice this will not create document it will just create reference so we can get our new id from it
val newMatchId = matchRef.id //this is new uniqe id from firebase like "8tmitl09F9rL87ej27Ay"
該文檔尚未創建,我們只是有一個新的 id,所以現在我們將此 id 添加到 POJO 類中(或者我猜它是 POKO,因為它是 Kotlin)。
class MatchInfo(
var player1Name: String? = null,
var player2Name: String? = null,
var player3Name: String? = null,
var player4Name: String? = null,
var firebaseId: String? = null, //this is new added string for our New ID
)
現在我們創建要上傳到 firebase 的對象:
val matchInfo = MatchInfo(player1?.mName, player2?.mName, player3?.mName, player4?.mName, newMatchId)
或者我們在將對象發送到 firebase 之前設置新的 id
matchInfo.firebaseId = newMatchId
現在我們使用新 ID 將對象發送到 firebase,如下所示:
val matches = mFirestore.collection(FirebaseHelp().USERS).document(user.uid).collection(FirebaseHelp().MATCHES)
matches.document(newMatchId).set(matchInfo) // this will create new document with name like"8tmitl09F9rL87ej27Ay" and that document will have field "firebaseID" with value "8tmitl09F9rL87ej27Ay"
添加回答
舉報